Java自学笔记 (1)
Java Ecosystem
Core components - Java Development Kit (JDK)
Java Compiler/javac
Java Runtime Environment (JRE)
- Encompasses Java Virtual Machine (JVM) and core libraries
- Required for running applications
Utilities
Command-line tools ```
- JDK | - Containing JRE + development tools | |_ JRE | - Provides libraries and components to run Java applications | - Not include development tools |_ JVM | - Executes Java bytecode ```
Frameworks
Spring
Dependency Injection (DI)
Promotes loosely coupled code
Aspect-Oriented Programming (AOP)
Separates cross-cutting concerns from business logic
Spring Boot
simplifies application setup with embedded servers and pre-configuration
Spring Model-View-Controller (MVC)
Streamlines web application development
Hibernate
Object-relational mapping (ORM) framework
Simplifies data handling by automating mapping objects to database tables
Build tools
Maven
Simplifies project management with features, such as:
- Dependency management
- Standardized build lifecycle
Gradle
- Incremental builds and multi-project support
- Uses Groovy or Kotlin for build scripts
Application servers
Provide environments for deploying and managing applications
Apache Tomcat
- Open-source, servlet container
- Ideal for small to medium-sized applications
JBoss
- Supports Java EE stack
- Suitable for large-scale enterprise applications
Testing frameworks
Junit
Creates repeatable tests, using annotations and assertions
TestNG
Offers data-driven testing and parallel test execution
Exceptions
Two types of exceptions regarding compiling
Checked exceptions
Checked at compile-time. Must be handled or declared.
Unchecked exceptions (Runtime exceptions)
NOT checked at compile-time. Not need to be handled or declared.
Blocks
Try block
Contains code that might throw an exception. -> Will cause termination if not catching the error
Catch block
Handles the exception if it occurs.
Finally block
Executes regardless of whether an exception occurred. ```flowchart TD flowchart TD A[异常发生] –> B{异常类型}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
B -->|Checked Exception| C[编译时强制处理]
C --> D[程序继续运行]
B -->|Unchecked Exception| E{是否捕获?}
E -->|是| F[程序继续运行]
E -->|否| G[程序异常终止]
B -->|Error| H{是否捕获?}
H -->|是| I[程序可能继续<br/>但状态不稳定]
H -->|否| J[程序终止]
style G fill:#ff9999
style J fill:#ff9999
style I fill:#ffcc99
style D fill:#99ff99
style F fill:#99ff99 ``` ### Throw The throws keyword is used in method declarations to indicate that a method can throw one or more exceptions.
OOP in Java
Access Modifier
Public
Private
Protected
- Allows access within the same package.
- Enables access to subclasses outside the package.
Default
- Used when no access modifier is specified.
- Allows access only within the same package.
1 2 3 4 5 6
class Car { String model; void displayModel() { System.out.println("Car Model: " + model); } }
Idea of encapsulation and modulation
- public = 对外公开的API
- default = package内部的实现细节
- private = 类内部的实现细节
- protected = 继承体系内的实现细节
Non-Access Modifier
Static
- Implies that a member belongs to a class, not to instances.
- Allows access without creating an object.
- Static variables are shared across all instances of a class.
public class Car { static int numberOfCars = 0; public Car() { numberOfCars++; } static void displayCount() { System.out.println("Total Cars: " + numberOfCars); } } - Variable values cannot be changed.
- Method cannot be overridden.
- Class cannot be subclassed.
1 2 3 4 5 6
public final class Vehicle { final int maxSpeed = 120; //maxSpeed cannot change final void displayMaxSpeed() { System.out.println("Max Speed " + maxSpeed); } }
- Cannot be instantiated.
- Must be extended.
- Must be implemented in subclasses.
1 2 3 4 5 6 7 8 9
public abstract class Shape { abstract void draw(); } public class Circle extend Shape { @Override void draw() { System.out.println("Drawing Circle"); } }
- Abstract class serves as a blueprint
- Abstract method
drawmust be implemented by any subclass
Constructors
- Create and initialize objects.
- Set up the object’s initial state by assigning values to its attributes.
characteristics
- Same name as the class
- no return type, no void keyword
- automatically invoked - crucial for initializing objects
- can be overloaded - allows multiple constructors
Default constructor
Java自动生成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Dog { String name; // default constructor Dog() { name = "Unknown"; } void display() { System.out.println("Dog's name: " + name); } } public class Main { public static void main(String[] args) { Dog myDog = new Dog(); // call the default constructor } }
Parameterized constructor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Dog { String name; // parameterized constructor Dog(String dogName) { name = dogName; } void display() { System.out.println("Dog's name: " + name); } } public class Main { public static void main(String[] args) { Dog myDog = new Dog("Buddy"); // call the parameterized constructor myDog.display(); } }
No-arg constructor
自己手写,可以自定义初始化哪些变量。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Car { String model; int year; // no-arg constructor Car() { model = "Default Model"; year = 2025; } void display() { System.out.println("Car Model: " + model + ", Year: " + year); } } public class Main { public static void main(String[] args) { Car myCar = new Car(); // call the no-args constructor } }
Inheritance
- Can inherit:
- public members
- protected members
- Cannot inherit:
- private members ```java // Superclass class Animal { String name; void eat() { System.out.println(name + “ is eating.”); } } // Subclass class Dog extends Animal { void bark() { System.out.println(name + “says woof!”); } }
/* How to use */ public class Main { public static void main(String[] args) { Doge myDog = new Dog(); myDog.name = “Buddy”; myDog.eat(); // inherited method from Animal myDog.bark(); // method from Dog class } }
1
2
3
4
5
6
7
8
9
10
11
## Types of Inheritance
### Single inheritance
- Allows inheritance from just **one** superclass, simplifying the structure.
### Multilevel inheritance
- Builds on single inheritance by allowing subclasses to inherit from other subclasses.
```java
class Puppy extends Dog {
void weep() {
System.out.println(name + " is weeping.");
}
}
Hierarchical inheritance
- Allows inheritance from common superclass.
- Enable shared functionality.
1 2 3 4 5
class Cat extends Animal { void meow() { System.out.println(name + " says meow!"); } }
Multiple inheritance
- Allows inheritance from multiple superclasses.
- Implemented using interfaces.
- Offer flexibility. ```java // Interface for devices that can be turned on/off interface Switchable { void turnOn(); void turnOff(); }
// Interface for devices with adjustable settings interface Adjustable { void increase(); void decrease(); }
// Interface for devices that can connect to a network interface Connectable { void connect(); void disconnect(); }
// SmartBulb class implementing all three interfaces class SmartBulb implements Switchable, Adjustable, Connectable { private boolean isOn = false; private int brightness = 50; // Default brightness level private boolean isConnected = false;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Switchable methods
@Override
public void turnOn() {
isOn = true;
System.out.println("SmartBulb is turned ON.");
}
@Override
public void turnOff() {
isOn = false;
System.out.println("SmartBulb is turned OFF.");
}
// Adjustable methods
@Override
public void increase() {
if (brightness < 100) {
brightness += 10;
System.out.println("Brightness increased to " + brightness + "%.");
} else {
System.out.println("Brightness is already at maximum.");
}
}
@Override
public void decrease() {
if (brightness > 0) {
brightness -= 10;
System.out.println("Brightness decreased to " + brightness + "%.");
} else {
System.out.println("Brightness is already at minimum.");
}
}
// Connectable methods
@Override
public void connect() {
isConnected = true;
System.out.println("SmartBulb is connected to the network.");
}
@Override
public void disconnect() {
isConnected = false;
System.out.println("SmartBulb is disconnected from the network.");
} }
// DimmableBulb class implementing two interfaces class DimmableBulb implements Switchable, Adjustable { private boolean isOn = false; private int brightness = 50; // Default brightness level
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Switchable methods
@Override
public void turnOn() {
isOn = true;
System.out.println("DimmableBulb is turned ON.");
}
@Override
public void turnOff() {
isOn = false;
System.out.println("DimmableBulb is turned OFF.");
}
// Adjustable methods
@Override
public void increase() {
if (brightness < 100) {
brightness += 10;
System.out.println("Brightness increased to " + brightness + "%.");
} else {
System.out.println("Brightness is already at maximum.");
}
}
@Override
public void decrease() {
if (brightness > 0) {
brightness -= 10;
System.out.println("Brightness decreased to " + brightness + "%.");
} else {
System.out.println("Brightness is already at minimum.");
}
} }
// RegularBulb class implementing one interface class RegularBulb implements Switchable { private boolean isOn = false;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Switchable methods
@Override
public void turnOn() {
isOn = true;
System.out.println("RegularBulb is turned ON.");
}
@Override
public void turnOff() {
isOn = false;
System.out.println("RegularBulb is turned OFF.");
} } ``` ## Method overriding ```java // Superclass class Animal {
void sound() {
System.out.println("Animal makes a sound.");
} } // Subclass class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks.");
} }
public class Main { public static void main(String[] args) { Animal myAnimal = new Animal(); Animal myDog = new Dog(); // Upcasting myAnimal.sound(); // Outputs: Animal makes a sound. myDog.sound(); // Outputs: Dog barks. } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
>Upcasting: 写`Animal myDog = new Dog();`,而不写`Dog myDog = new Dog();`。 这种写法体现了Java的多态性(Polymorphism):
> - 向上转型(Upcasting):子类对象可以被赋值给父类类型的变量
> - 好处:代码更灵活,可以统一处理不同的子类对象
# Polymorphism
- Polymorphism is a process that allows objects to **share the same interface** while exhibiting different behaviors based on their specific implementations.
- Enables flexibility and reusability.
## Types pf polymorphism
### Compile-time polymorphism / Method Overloading (重载)
- Occurs when **multiple methods belonging to the same class, have the same name, but ==differ in the number or type of parameters==**.
```java
class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two double values
double add(double a, double b) {
return a + b;
}
}
Runtime polymorphism / Method overriding (覆写)
- Occurs when a subclass provides its specific implementation of a method defined in its superclass.
- At runtime, the method to be executed is dynamically determined depending on the actual type of the object.
- Allows for flexible and dynamic behavior.
Virtual Method
- Any method that can be overridden in a subclass, enabling dynamic method resolution.
- By default, consider all non-static method as virtual, ensuring subclass’s method is executed at runtime, regardless of the reference type.
- Example to [[#Method overriding|Method Overriding Example]]: Method
sound()is a virtual method.Abstraction
Mode of operation.
- Achieved through interfaces and abstract classes.
- Defines methods that subclasses must implement.
- Hides the complex details of how those methods work.
Interface in Java
- Defines a contract for classes to follow.
- Contains:
- Constants
- Method signatures
- Allows only method declarations without bodies
- Provides a blueprint for implementing classes
- Default/static methods
- Nested types
- Cannot have instance fields or constructors.
- Default: all methods in an interface are public.
Abstract class
- Cannot be instantiated directly
- Can contain abstract methods that must be implemented by subclasses and concrete methods that can be used or overridden.
- Helps define common behavior cross related classes.
- Characteristics:
- Abstract methods:
- Must be implemented by subclasses
- Concrete methods:
- Can be used or overridden by subclasses
- Support single inheritance:
- Can extend only one abstract class ```java abstract class Shape { abstract void draw(); //abstract method void display() { //concrete method System.out.println(“This is a shape.”); } } // Concrete subclass class Circle extends Shape { void draw(){ System.out.println(“Drawing circle”); } }
- Abstract methods:
public class Main { public static void main(String[] args) { Shape shape = new Circle(); shape.draw(); shape.display(); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Inner Classes
- Defined as a class within another class
- Can access variables and methods of outer class directly
- Logically group classes only used in one place
```java
class OuterClass {
int outerVariable = 10;
class InnerClass {
void display() {
System.out.println("Outer variable value: " + outerVariable);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass(); // First, create an instance of OuterClass
OuterClass.InnerClass inner = outer.new InnerClass(); // Then, create an instance of InnerClass by referring to OuterClass
inner.display();
}
}
Types of Inner Classes
Non-static inner class
- Most common type
- Can access static and non-static members of outer class
Static nested class
- Use keyword
static Cannot access non-static members of the outer class directly ```java class OuterClass { static int staticVariable = 20;
static class StaticNestedClass { void show() { System.out.println(“Static variable value: “ + staticVariable); } } }
// No need to create an instance of the outer class public class Main { public static void main(String[] args) { OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass(); nested.show(); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
### Method-local inner class
- Defined **within a method** of the outer class
- Can only be accessed within that method(相当于是method内部的helper)
```java
class OuterClass {
void myMethod() {
class MethodLocalInner {
void display() {
System.out.println("Inside Method Local Inner Class");
}
}
MethodLocalInner inner = new MethodLocalInner();
inner.display();
}
}
Anonymous inner class
- Instantiates a class not reused elsewhere
- It’s often used when you need to create a subclass or implement an interface on the fly(动态接口) - GUI application (组件/按钮很多,需要对每个按钮监听接口,用anonymous inner class可以少写很多外部类) ```java interface Greeting { void greet(); }
public class Main { public static void main(String[] args) { // 方法1:传统方式 Greeting greeting1 = new Greeting() { public void greet() { System.out.println(“Hello from Anonymous Inner Class!”); } }; // 注意这里的分号
1
2
3
4
5
6
7
8
9
greeting1.greet();
// 方法2:也可以直接调用
new Greeting() {
public void greet() {
System.out.println("Direct call!");
}
}.greet(); // 直接调用方法
} } ``` ## When to use inner classes - **Encapsulation**: Hiding implementation details of outer class - **Logical grouping**: For classes only relevant to their outer class - **Access to outer class members**: Without passing the members around - **Event handling**: (graphic designing) - **Data structure implementation**: For nodes or elements (in trees or linked list)
Collections
Framework (Java Collections Framework - JCF)
Types of Java Collections
| ==Types== | ==Collection Type== | ==Capabilities== | ==Common Implementations== | | ———— | ——————- | —————————————————————— | ————————— | | ==List== | Ordered | - Allow duplicated elements
- Maintain order | - ArrayList
- LinkedList | | ==Sets== | Unordered | Do not allow duplicate elements | - HashSet
- TreeSet | | ==Maps== | Unordered | - Key-value pairs where each key is unique
- Allows null values | - HashMap
- TreeMap |
List
ArrayList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.ArrayList;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
// Creating a List
List<String> fruits = new ArrayList<>();
// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Displaying the List
System.out.println("Fruits: " + fruits);
// Accessing an element
String firstFruit = fruits.get(0);
System.out.println("First fruit: " + firstFruit);
// Remove an element
fruits.remove("Banana");
}
}
- Dynamic array: resize automatically
- Facilitates fast access to elements
- ==Unsuitable for frequent modification==
LinkedList
```java import java.util.LinkedList;
public class LinkedListExample { public static void main(String[] args) { // Creating a LinkedList LinkedList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Adding elements
animals.add("Dog");
animals.add("Cat");
animals.add("Elephant");
// Displaying the LinkedList
System.out.println("Animals: " + animals);
// Access an element
System.out.println("First color: " + animals.get(0));
// Remove an element
colors.remove("Green");
} } ``` - Uses a ==doubly linked list== to store elements - Offers dynamic resizing, enables faster insertions and deletions than ArrayLists - Ideal for ==queue== operations #### List Selection **ArrayList**: - Use when elements need to be accessed quickly - Use when maintaining a ==stable list size== **LinkedList**: - Use when elements need to be added or removed frequently - Use ==when implementing== data structures such as ==stacks or queues== #### Queue - **Enqueue**: Adds an item to the back of the queue - **Dequeue**: Removes an items from the front of the queue - **FIFO**: First In First Out ```java import java.util.LinkedList; import java.util.Queue;
public class QueueExample { public static void main(String[] args) { // Creating a Queue Queue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Enqueue operation
customerQueue.offer("Customer 1");
customerQueue.offer("Customer 2");
customerQueue.offer("Customer 3");
// Displaying the Queue
System.out.println("Queue: " + customerQueue);
// Dequeue operation
String servedCustomer = customerQueue.poll();
System.out.println("Serving: " + servedCustomer);
// Displaying the Queue after Dequeue
System.out.println("Queue after dequeue: " + customerQueue);
} } ``` ### Sets
| HashSet | TreeSet | | ————————— | —————————- | | Does not maintain any order | Maintains a ==sorted order== | | Allows ==null== values | Does not allow null values |
HashSets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
// Creating a HashSet
HashSet<String> colors = new HashSet<>();
// Adding elements
colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.add("Red"); //Duplicate
// Displaying the HashSet
System.out.println("Colors: " + colors); //Print unique colors (ignores the duplicated "Red")
// Checking if an element exists
if (colors.contains("Green")) {
System.out.println("Green is present in the set");
}
// Removing an element
colors.remove("Blue");
System.out.println("After removal: " + colors);
}
}
TreeSets
- Implements a red-black tree structure (用红黑树自动排序)
- ==Maintains a sorted order== of elements based on their natural ordering or a specified comparator
- Does not allow duplicate elements
- Provides ==logarithmic time performance in
O(log n)== for basic operations - Does not allow null elements ```java import java.util.TreeSet;
public class TreeSetExample { public static void main(String[] args) { // Creating a TreeSet TreeSet
1
2
3
4
5
6
7
8
9
10
11
12
13
// Displaying the TreeSet
// Output: Numbers in TreeSet: [1, 3, 5, 8]
System.out.println("Numbers in TreeSet: " + numbers);
// Checking if an element exists
if (numbers.contains(5)) {
System.out.println("5 is present in the set.");
}
// Removing an element
// Output: After removal: [1, 3, 5]
numbers.remove(8);
System.out.println("After removal: " + numbers);
} } ``` ### Maps 只有map是用`.put` 来添加元素的。 ```java import java.util.HashMap;
public class HashMapExample { public static void main(String[] args) { // Creating a HashMap HashMap<String, Integer> ageMap = new HashMap<>();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Adding key-value pairs
ageMap.put("Alice", 30);
ageMap.put("Bob", 25);
ageMap.put("Charlie", 35);
// Displaying the HashMap
System.out.println("Age Map: " + ageMap);
// Accessing a vlue by key
int aliceAge = ageMap.get("Alice");
System.out.println("Alice's Age: " + aliceAge);
// Iterating through the HashMap
for (String key : ageMap.keySet()) {
System.out.println(key + ": " + ageMap.get(key));
}
// Checking if a key exists
if (ageMap.containsKey("Bob")) {
System.out.println("Bob exists in the map.");
}
// Removing a key-value pair
ageMap.remove("Charlie");
} } ``` #### HashMap - Enables ==effective counting== of items, such as word frequency - Implements dictionaries or associative arrays - Ensures fast access to elements - Works in scenarios where ==the order of elements does **not** matter== - Supports storing null values or a single null key - Handles large datasets efficiently ```java HashMap<String, Integer> wordCount = new HashMap<>();
String text = “appple banana apple orange banana apple”; String[] words = text.split(“ “); for (String word : words) { wordCount.put(word, wordCount.getOrDefault(word, 0) + 1); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#### TreeMap
```java
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
// Creating a TreeMap
TreeMap<String, Integer> treeMap = new TreeMap<>();
// Adding key-value pairs to the TreeMap
treeMap.put("Banana", 2);
treeMap.put("Apple", 1);
treeMap.put("Cherry", 3);
// Accessing values
System.out.println("Value for key 'Apple': " + treeMap.get("Apple"));
// Iterating through the TreeMap
/* Output:
Apple: 1
Banana: 2
Cherry: 3 */
for (String key : treeMap.keySet()) {
System.out.println(key + ": " + treeMap.get(key));
}
//Removing a key-value pair
treeMap.remove("Banana");
}
}
- Maintains a sorted list of items for ==ordered display==
- Ideal for ==implementing priority queues== where order matters
- Stores data requiring frequent range queries or a sorted view ```java TreeMap<String, Integer> leaderboard = new TreeMap<>();
leaderboard.put(“Alice”, 150); leaderboard.put(“Bob”, 200); leaderboard.put(“Charlie”, 100);
// Displaying sorted leaderboard for (String player : leaderboard.keySet()) { System.out.println(player + “: “ + leaderboard.get(player)); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
## Applications
- Library management systems: ArrayList
- store books dynamically
- access books by indices
- E-commerce applications: HashMap
- store customer orders
- allowing for quick retrieval using order IDs
- Employee management system: HashSet
- store employee names uniquely
- Task management system: LinkedList
- efficiently manage tasks
- allowing for easy addition and removal
- Social media apps: HashMap & HashSet
- HashMap: manage user followers, ensuring fast lookups
- HashSet: prevent duplicated followers
# File Handling
## Examples
### Example 1
```java
import java.io.File;
public class FileExample {
public static void main(String[] args) {
File myFile = new File("example.txt"); //file path, doesn't creat file
// Check if the file exists
if (myFile.exists()) {
System.out.println("File exists.");
} else {
System.out.println("File does not exist.");
}
}
}
Example 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.io.BufferedWritter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("output.txt");
BufferedWritter bufferedWritter = new BufferedWritter(writer);
bufferedWritter.write("Hello World!");
bufferedWritter.newLine();
bufferedWritter.write("This is a Java file handling example.");
bufferedWritter.close();
System.out.println("Data written to file successully.");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
FileWriterobject- handles file output
- creates a file if it doesn’t exist
- ==overwrites== existing files
BufferedWritter
public class ReadFromFile { public static void main(String[] args) { try { FileReader reader = new FileReader(“output.txt”); BufferedReader bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); } catch (IOException e) { System.out.println(“An error occurred: “ + e.getMessage()); } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
- `FileReader`
- Creates and reads file
## Byte Streams
Byte streams move **raw bytes of data** through the system.
- reads and writes data
- used across tasks
- handles all types of data
### Applications
- read and write files, including ==images and videos==
- facilitate network programming
- enable transmission and reception of data
- support ==serialization==
- convert objects into byte format
- enable multimedia applications
- process and manipulate data
## Directories
- organize files
- make file access easier
- ensure efficiency in handling data
```java
import java.io.File;
public class DirectoryExample {
public static void main(Stirng[] args) {
// Define the directory path
String directoryPath = "Projects/Java";
// Create a File object
File directory = new File(directoryPath);
// Create the directory
if (!directory.exists()) {
boolean created = directory.mkdirs();
if (created) {
System.out.println("Directory created successfully: " + directoryPaht);
} else {
System.out.println("Directory already exists: " + directoryPath);
}
}
// List all the files and directories in the specific directory
String[] contents = directory.list();
if (content != null) {
System.out.println("Contents of " + directoryPath + ":");
for (String fileName : contents) {
System.out.println(fileName);
}
} else {
System.out.println("The directory is empty or does not exist.");
}
// Deletion
// Checks if the directory exists
if (directory.exists()) {
boolean deleted = directory.delete();
if (deleted) {
System.out.println("Directory deleted successfully: " + directoryPath);
} else {
System.out.println("Failed to delete directory. It may not be empty.");
}
} else {
System.out.println("Directory does not exist: " + directoryPath);
}
}
}
mkdirs():- creates ==directory and missing parent directory==
- The program checks if the directory already exists before attempting to create it
Trueif the directory is successfully createdFalseif the directory fails to be created. Possible reasons can be:- No authority
- Path invalid
- Cannot create directory at some parent level
delete():- ==requires empty directory==
- The program checks that the directory exists before attempting deletion
Trueif the deletion is successfulFalseif the deletion is failed -> developers can be notifiedjava.nio
==More powerful== ```java import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.IOException;
public class CreateDirectoryNIO { public static void main(String[] args) { Path path = Paths.get(“Projects/NioExample”); try { // Create the directory using NIO Path createDir = Files.createDirectories(path); System.out.println(“Directory created successfully: “ + createDir.toString()); } catch (IOException e) { System.err.println(“Failed to create directory: “ + e.getMessage()); } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- `Paths.get()`:
- creates a Path object
- can be used in various operations like reading, writing, or creating directories
- represents directory path
- `Files.createDirectories()`
- creates directories and parent directories
# Data and Time Handling
## Classes
### LocalDate
```java
import java.time.LocalDate;
public class LocalDateExample {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Today's date: " + today); //output format: YYYY:MM:DD
}
}
LocalTime
1
2
3
4
5
6
7
import java.time.LocalDateTime;
public class LocalDateTimeExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("Current date and time: " + now); //time output format: HH:MM:NNN (current test output: 2025-07-16T13:59:46.295888300)
}
}
ZoneDateTime
1
2
3
4
5
6
7
import java.time.ZonedDateTime;
public class ZonedDateTimeExample {
public static void main(String[] args) {
ZonedDateTime zonedNow = ZonedDateTime.now();
System.out.println("Current date and time with zone: " + zonedNow); //current test output: 2025-07-16T14:04:13.805139400+01:00[Europe/Dublin]
}
}
Formatting Dates
1
2
3
4
5
6
7
8
9
10
11
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateFormattingExample {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formattedDate = currentDate.format(formatter);
System.out.println("Formatted Date: " + formattedDate);
}
}
Time Zones
- ZoneId:
- represents a time zone identifier (America/New York, Europe/London)
- ZonedDateYime
- ZoneOffset
- OffsetDateTime
1 2 3 4 5 6 7 8 9 10 11
import java.time.ZoneId; import java.time.ZonedDateTime; public class TimeZoneExample { public static void main(String[] args) { ZoneId newYorkZone = ZoneId.of("America/New_York"); System.out println("Time Zone ID: " + newYorkZone); //output: Time Zone ID: America/New_York ZonedDateTime newYorkTime = ZonedDateTime.now(ZoneId.of("America/New_York")); System.out.println("Current Date and Time in New York: " + newYorkTime); //output: Current date and time in New York: 2025-07-16T09:27:21.722897300-04:00[America/New_York] } }
Time zones: Scheduling meetings
```java import java.time.ZonedDateTime; import java.time.ZonedId; import java.time.format.DateTimeFormatter;
public class ConferenceScheduler { public static void main(String[] args) { ZonedDateTime meetingTimeUTC = ZonedDateTime.parse(“2024-12-30T15:00:00Z”); String[] participantTimeZones = { “America/New_York”, //Eastern Standart Time (EST) “Europe/London”, //Greenwich Mean Time (GMT) “Aisa/Kolkata”, //Indian Standard Time (IST) “Australia/Sydney” //Australian Eastern Daylight Time (AEDT) }; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss z”); System.out.println(“Meeting Time in UTC: “ + meetingTimeUTC.format(formatter)); for (String timeZone : participantTimeZones) { ZonedDateTime localTime = meetingTimeUTC.withZoneSameInstant(ZoneId.of(timeZone)); System.out.println(“Meeting Time in “ + timeZone + “: “ + localTime.format(formatter)); } } } ```