Java File Handling

In Java, file handling is performed using classes from the java.io package. Here are some key points:

File Class:

  • The File class represents a file or directory pathname.
  • It can be used to create, delete, rename, or check the existence of files and directories.
  • Example:
import java.io.File;

File file = new File("example.txt");

File Input/Output Streams:

  • Input/output streams are used to read from or write to files.
  • The FileInputStream and FileOutputStream classes are used for binary file I/O, while FileReader and FileWriter classes are used for text file I/O.
  • Example:
import java.io.FileInputStream;
import java.io.FileOutputStream;

FileInputStream inputStream = new FileInputStream("input.txt");
FileOutputStream outputStream = new FileOutputStream("output.txt");

Buffered Streams:

  • Buffered streams (BufferedReader, BufferedWriter, BufferedInputStream, BufferedOutputStream) provide better performance by buffering data in memory before reading from or writing to a file.
  • Example:
import java.io.BufferedReader;
import java.io.FileReader;

BufferedReader reader = new BufferedReader(new FileReader("input.txt"));

Reading and Writing Files:

  • Files can be read using methods like read(), readLine(), or read(byte[]).
  • Writing to files is done using methods like write().
  • Example:
int data = inputStream.read();
String line = reader.readLine();
outputStream.write(data);

File Operations:

  • File operations such as creating, deleting, renaming, or checking file existence can be performed using File class methods like createNewFile(), delete(), renameTo(), exists().
  • Example:
File file = new File("example.txt");
boolean created = file.createNewFile();

 

Summary

File handling in Java allows for the manipulation and processing of files and directories. Understanding how to use file-related classes and methods is essential for reading from and writing to files in Java applications.