Java File I/O (NIO.
2), Serialization, Concurrency, and Synchronization
1. File I/O (NIO.2)
### Introduction to NIO.2
Java NIO (New I/O) was introduced in JDK 1.4 and enhanced in JDK 7 with NIO.2 to address
limitations in standard I/O ([Link] package).
Key Concepts
Path, Files, FileChannel, AsynchronousFileChannel.
Creating and Writing to Files
```java
import [Link].*;
import [Link];
public class FileWriteExample {
public static void main(String[] args) {
Path path = [Link]("C:/example/[Link]");
String content = "Hello, NIO.2!";
try {
[Link](path, [Link](), [Link]);
[Link]("File written successfully!");
} catch (IOException e) {
[Link]();
}
}
}
```
2. Serialization and Deserialization
### Definition
- **Serialization:** Process of converting an object into a byte stream.
- **Deserialization:** Process of converting a byte stream back to an object.
Serialization Example
```java
import [Link].*;
class Person implements Serializable {
String name;
int age;
Person(String name, int age) {
[Link] = name;
[Link] = age;
}
}
public class SerializeExample {
public static void main(String[] args) {
try {
Person person = new Person("John", 30);
FileOutputStream fileOut = new FileOutputStream("[Link]");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
[Link](person);
[Link]();
[Link]();
[Link]("Object serialized successfully!");
} catch (IOException e) {
[Link]();
}
}
}
```
3. Concurrency and Multithreading
### Definition
- **Concurrency:** Ability to run multiple threads simultaneously.
- **Multithreading:** Multiple threads executing different parts of a program concurrently.
4. Synchronization and Locks
### Definition
- **Synchronization:** Mechanism to ensure that multiple threads access shared resources
in a thread-safe manner.
- **Lock:** Provides more control over synchronization.