0% found this document useful (0 votes)
5 views2 pages

Java Fileio Concurrency

Uploaded by

firekirtans
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Java Fileio Concurrency

Uploaded by

firekirtans
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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 (java.io package).

Key Concepts
Path, Files, FileChannel, AsynchronousFileChannel.

Creating and Writing to Files


```java
import java.nio.file.*;
import java.io.IOException;

public class FileWriteExample {


public static void main(String[] args) {
Path path = Paths.get("C:/example/test.txt");
String content = "Hello, NIO.2!";
try {
Files.write(path, content.getBytes(), StandardOpenOption.CREATE);
System.out.println("File written successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```

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 java.io.*;

class Person implements Serializable {


String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}

public class SerializeExample {


public static void main(String[] args) {
try {
Person person = new Person("John", 30);
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
System.out.println("Object serialized successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```

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.

You might also like