Skip to content

Commit 84eec58

Browse files
committed
file-handling
1 parent b856a61 commit 84eec58

6 files changed

+540
-6
lines changed

docs/java/file-handling-and-io/reading-and-writing-files.md

Lines changed: 94 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,97 @@ sidebar_label: Reading and Writing Files
55
sidebar_position: 2
66
tags: [java, file handling, io, programming, java file handling, java io]
77
description: In this tutorial, you will learn how to read from and write to files in Java. We will learn how to read text files, binary files, and write to text files using Java.
8-
---
8+
---
9+
10+
# Reading and Writing Files in Java
11+
12+
## Introduction
13+
14+
Reading and writing files is a common task in Java programming. Java provides several classes for handling file I/O operations, such as `FileInputStream`, `FileOutputStream`, `BufferedReader`, `BufferedWriter`, `FileReader`, and `FileWriter`. This guide covers basic file reading and writing operations using these classes.
15+
16+
## 1. Reading Files
17+
18+
### Reading Text Files
19+
20+
```java
21+
import java.io.BufferedReader;
22+
import java.io.FileReader;
23+
import java.io.IOException;
24+
25+
public class ReadTextFileExample {
26+
public static void main(String[] args) {
27+
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
28+
String line;
29+
while ((line = reader.readLine()) != null) {
30+
System.out.println(line);
31+
}
32+
} catch (IOException e) {
33+
System.out.println("An error occurred: " + e.getMessage());
34+
}
35+
}
36+
}
37+
```
38+
39+
### Reading Binary Files
40+
41+
```java
42+
import java.io.FileInputStream;
43+
import java.io.IOException;
44+
45+
public class ReadBinaryFileExample {
46+
public static void main(String[] args) {
47+
try (FileInputStream fis = new FileInputStream("example.bin")) {
48+
int byteData;
49+
while ((byteData = fis.read()) != -1) {
50+
System.out.print((char) byteData);
51+
}
52+
} catch (IOException e) {
53+
System.out.println("An error occurred: " + e.getMessage());
54+
}
55+
}
56+
}
57+
```
58+
59+
## 2. Writing Files
60+
61+
### Writing Text Files
62+
63+
```java
64+
import java.io.BufferedWriter;
65+
import java.io.FileWriter;
66+
import java.io.IOException;
67+
68+
public class WriteTextFileExample {
69+
public static void main(String[] args) {
70+
try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {
71+
writer.write("Hello, World!");
72+
writer.newLine();
73+
writer.write("This is a new line.");
74+
} catch (IOException e) {
75+
System.out.println("An error occurred: " + e.getMessage());
76+
}
77+
}
78+
}
79+
```
80+
81+
### Writing Binary Files
82+
83+
```java
84+
import java.io.FileOutputStream;
85+
import java.io.IOException;
86+
87+
public class WriteBinaryFileExample {
88+
public static void main(String[] args) {
89+
try (FileOutputStream fos = new FileOutputStream("example.bin")) {
90+
byte[] data = { 72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33 };
91+
fos.write(data);
92+
} catch (IOException e) {
93+
System.out.println("An error occurred: " + e.getMessage());
94+
}
95+
}
96+
}
97+
```
98+
99+
## Conclusion
100+
101+
Reading and writing files in Java is straightforward using the classes provided in the `java.io` package. Whether you need to handle text files or binary files, Java provides the necessary tools to perform file I/O operations efficiently. By understanding and using these classes effectively, you can manipulate files in your Java applications with ease.

docs/java/file-handling-and-io/serialization-and-deserialization.md

Lines changed: 86 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,89 @@ sidebar_label: Serialization and Deserialization
55
sidebar_position: 3
66
tags: [java, file handling, serialization, deserialization]
77
description: In this tutorial, you will learn about serialization and deserialization in Java. We will learn how to serialize and deserialize objects in Java using the `Serializable` interface and the `ObjectInputStream` and `ObjectOutputStream` classes.
8-
---
8+
---
9+
10+
# Serialization and Deserialization in Java
11+
12+
## Introduction
13+
14+
Serialization is the process of converting Java objects into a stream of bytes, which can be saved to a file, sent over the network, or stored in a database. Deserialization is the reverse process of converting a stream of bytes back into Java objects. Serialization is commonly used for data persistence, caching, and communication between distributed systems.
15+
16+
## Serialization
17+
18+
### Serialization Process
19+
20+
To serialize an object in Java, you need to implement the `Serializable` interface. The object's class and all of its member variables must be serializable.
21+
22+
```java
23+
import java.io.FileOutputStream;
24+
import java.io.ObjectOutputStream;
25+
import java.io.Serializable;
26+
27+
public class SerializationExample {
28+
public static void main(String[] args) {
29+
try (FileOutputStream fos = new FileOutputStream("data.ser");
30+
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
31+
MyClass obj = new MyClass();
32+
oos.writeObject(obj);
33+
System.out.println("Object serialized successfully");
34+
} catch (Exception e) {
35+
System.out.println("An error occurred: " + e.getMessage());
36+
}
37+
}
38+
}
39+
40+
class MyClass implements Serializable {
41+
// Serializable class
42+
private int id;
43+
private String name;
44+
// Constructors, methods, etc.
45+
}
46+
```
47+
48+
## Deserialization
49+
50+
### Deserialization Process
51+
52+
To deserialize an object in Java, you need to read the serialized data from a file or stream and convert it back into an object. The object's class must be available in the classpath.
53+
54+
```java
55+
import java.io.FileInputStream;
56+
import java.io.ObjectInputStream;
57+
58+
public class DeserializationExample {
59+
public static void main(String[] args) {
60+
try (FileInputStream fis = new FileInputStream("data.ser");
61+
ObjectInputStream ois = new ObjectInputStream(fis)) {
62+
MyClass obj = (MyClass) ois.readObject();
63+
System.out.println("Object deserialized successfully");
64+
} catch (Exception e) {
65+
System.out.println("An error occurred: " + e.getMessage());
66+
}
67+
}
68+
}
69+
```
70+
71+
### Serialization ID
72+
73+
Java objects have a unique identifier called a Serialization ID (serialVersionUID), which is used during deserialization to ensure compatibility between serialized and deserialized objects. It's recommended to explicitly declare this ID to prevent versioning issues.
74+
75+
```java
76+
private static final long serialVersionUID = 123456789L;
77+
```
78+
79+
## Best Practices
80+
81+
1. **Implement Serializable**: Ensure that the class you want to serialize implements the `Serializable` interface.
82+
83+
2. **Handle Versioning**: Declare a `serialVersionUID` to control versioning and prevent compatibility issues.
84+
85+
3. **Handle Transient Fields**: Use the `transient` keyword to exclude fields from serialization that are not relevant for persistence.
86+
87+
4. **Close Resources**: Always close streams and resources properly after serialization and deserialization.
88+
89+
5. **Consider Security**: Be cautious when deserializing data from untrusted sources to avoid security vulnerabilities.
90+
91+
## Conclusion
92+
93+
Serialization and deserialization are powerful features in Java for persisting and transferring object data. By following best practices and understanding the serialization process, you can efficiently store and retrieve objects in your Java applications.

docs/java/file-handling-and-io/working-with-files-and-directories.md

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,55 @@ sidebar_label: Working with Files and Directories
55
sidebar_position: 1
66
tags: [java, files, directories, programming, java files, java directories]
77
description: In this tutorial, we will learn how to work with files and directories in Java. We will learn how to read from and write to files, create directories, list files in a directory, and more.
8-
---
8+
---
9+
10+
# Working with Files and Directories in Java
11+
12+
## Introduction
13+
14+
Working with files and directories is a common task in Java programming. Java provides the `java.io` and `java.nio.file` packages to handle file and directory operations. This guide covers basic file and directory operations, such as creating, reading, writing, and deleting files and directories.
15+
16+
## 1. Creating Files and Directories
17+
18+
### Creating a File
19+
20+
```java
21+
import java.io.File;
22+
import java.io.IOException;
23+
24+
public class FileCreationExample {
25+
public static void main(String[] args) {
26+
try {
27+
File file = new File("example.txt");
28+
if (file.createNewFile()) {
29+
System.out.println("File created successfully");
30+
} else {
31+
System.out.println("File already exists");
32+
}
33+
} catch (IOException e) {
34+
System.out.println("An error occurred: " + e.getMessage());
35+
}
36+
}
37+
}
38+
```
39+
40+
### Creating a Directory
41+
42+
```java
43+
import java.io.File;
44+
45+
public class DirectoryCreationExample {
46+
public static void main(String[] args) {
47+
File directory = new File("example");
48+
if (directory.mkdir()) {
49+
System.out.println("Directory created successfully");
50+
} else {
51+
System.out.println("Failed to create directory");
52+
}
53+
}
54+
}
55+
```
56+
57+
## Conclusion
58+
59+
Java provides comprehensive APIs for working with files and directories, allowing you to perform various operations such as creating, reading, writing, and deleting files and directories. By understanding and using these APIs effectively, you can manipulate files and directories in your Java applications with ease.

docs/java/file-handling-and-io/working-with-io-channels.md

Lines changed: 111 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,114 @@ sidebar_label: Working with I/O Channels
55
sidebar_position: 4
66
tags: [java, io, channels, programming, java io, java channels]
77
description: In this tutorial, we will learn how to work with I/O channels in Java. We will learn what I/O channels are, how to create and use them, and how to read from and write to channels.
8-
---
8+
---
9+
10+
# Working with I/O Channels in Java
11+
12+
## Introduction
13+
14+
I/O channels provide a higher-level abstraction for reading from and writing to streams in Java. Java NIO (New I/O) provides the `java.nio.channels` package, which includes various channel classes for performing I/O operations efficiently. This guide covers basic operations with I/O channels, including reading from and writing to files.
15+
16+
## 1. Reading from Channels
17+
18+
### Reading from a File Channel
19+
20+
```java
21+
import java.io.FileInputStream;
22+
import java.io.IOException;
23+
import java.nio.ByteBuffer;
24+
import java.nio.channels.FileChannel;
25+
26+
public class ReadFromChannelExample {
27+
public static void main(String[] args) {
28+
try (FileInputStream fis = new FileInputStream("input.txt");
29+
FileChannel channel = fis.getChannel()) {
30+
ByteBuffer buffer = ByteBuffer.allocate(1024);
31+
int bytesRead = channel.read(buffer);
32+
while (bytesRead != -1) {
33+
buffer.flip();
34+
while (buffer.hasRemaining()) {
35+
System.out.print((char) buffer.get());
36+
}
37+
buffer.clear();
38+
bytesRead = channel.read(buffer);
39+
}
40+
} catch (IOException e) {
41+
System.out.println("An error occurred: " + e.getMessage());
42+
}
43+
}
44+
}
45+
```
46+
47+
## 2. Writing to Channels
48+
49+
### Writing to a File Channel
50+
51+
```java
52+
import java.io.FileOutputStream;
53+
import java.io.IOException;
54+
import java.nio.ByteBuffer;
55+
import java.nio.channels.FileChannel;
56+
57+
public class WriteToChannelExample {
58+
public static void main(String[] args) {
59+
try (FileOutputStream fos = new FileOutputStream("output.txt");
60+
FileChannel channel = fos.getChannel()) {
61+
String data = "Hello, World!";
62+
ByteBuffer buffer = ByteBuffer.wrap(data.getBytes());
63+
channel.write(buffer);
64+
System.out.println("Data written to file successfully");
65+
} catch (IOException e) {
66+
System.out.println("An error occurred: " + e.getMessage());
67+
}
68+
}
69+
}
70+
```
71+
72+
## 3. Closing Channels
73+
74+
### Closing a Channel
75+
76+
```java
77+
import java.io.IOException;
78+
import java.nio.channels.FileChannel;
79+
import java.nio.file.Paths;
80+
81+
public class CloseChannelExample {
82+
public static void main(String[] args) {
83+
try (FileChannel channel = FileChannel.open(Paths.get("file.txt"))) {
84+
// Channel operations
85+
} catch (IOException e) {
86+
System.out.println("An error occurred: " + e.getMessage());
87+
}
88+
}
89+
}
90+
```
91+
92+
## 4. File Channel Properties
93+
94+
### File Channel Properties
95+
96+
File channels provide various properties and methods for querying information about the channel, such as its size, position, and whether it is open.
97+
98+
```java
99+
import java.io.IOException;
100+
import java.nio.channels.FileChannel;
101+
import java.nio.file.Paths;
102+
103+
public class ChannelPropertiesExample {
104+
public static void main(String[] args) {
105+
try (FileChannel channel = FileChannel.open(Paths.get("file.txt"))) {
106+
System.out.println("File size: " + channel.size() + " bytes");
107+
System.out.println("Current position: " + channel.position());
108+
System.out.println("Is open? " + channel.isOpen());
109+
} catch (IOException e) {
110+
System.out.println("An error occurred: " + e.getMessage());
111+
}
112+
}
113+
}
114+
```
115+
116+
## Conclusion
117+
118+
I/O channels provide a powerful and efficient way to perform I/O operations in Java. By using file channels, you can read from and write to files with improved performance and flexibility. Understanding how to work with I/O channels is essential for developing high-performance Java applications.

0 commit comments

Comments
 (0)