File Handling

1. Introduction to File Handling

1.1 What is File Handling

File handling is the process of reading from and writing to files.

1.2 Why File Handling

  • Stores data permanently
  • Useful for large data storage
  • Enables data sharing between programs

1.3 Types of Files

  • Text files → readable content
  • Binary files → non-readable format

1.4 Java Package

Java provides java.io package for file handling.


2. Reading Files

2.1 Using FileReader

import java.io.FileReader;FileReader fr = new FileReader("file.txt");
int ch;
while ((ch = fr.read()) != -1) {
    System.out.print((char) ch);
}
fr.close();

2.2 Using Scanner

import java.io.File;
import java.util.Scanner;Scanner sc = new Scanner(new File("file.txt"));
while (sc.hasNextLine()) {
    System.out.println(sc.nextLine());
}
sc.close();

2.3 Key Points

  • Always close file
  • Handle exceptions

3. Writing Files

3.1 Using FileWriter

import java.io.FileWriter;FileWriter fw = new FileWriter("file.txt");
fw.write("Hello World");
fw.close();

3.2 Appending Data

FileWriter fw = new FileWriter("file.txt", true);
fw.write("New Data");
fw.close();

3.3 Important Notes

  • Use close() to save data
  • Use flush() if needed

4. File Streams

4.1 What are Streams

Streams are sequences of data.

4.2 Byte Streams

Used for binary data:

FileInputStream fis = new FileInputStream("file.txt");

4.3 Character Streams

Used for text data:

FileReader fr = new FileReader("file.txt");

4.4 Difference

Byte StreamCharacter Stream
Binary dataText data
InputStreamReader

5. Buffered Readers and Writers

5.1 BufferedReader

import java.io.*;BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();

5.2 BufferedWriter

BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"));
bw.write("Hello Buffered");
bw.close();

5.3 Advantages

  • Faster performance
  • Efficient reading/writing
  • Reads large data easily

Conclusion

File handling is an essential concept in Java that allows programs to interact with external files for data storage and retrieval. By understanding file reading, writing, streams, and buffering techniques, beginners can build real-world applications that manage data efficiently.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *