11
JulFile Handling in Java Complete Guide
File Handling in Java
Why is File Handling in Java Required?
- Data persistence: Saving data to files assures that it can be retrieved later, even if a program has stopped running.
- Data communication: Files enable data communication between different programs or systems.
- Large data storage: Files enable the storage of large datasets that would not fit in memory.
- Log management: Storing logs in files allows you to follow program activity and troubleshoot difficulties.
Key Concepts: Java I/O and Streams
- Byte Streams: Handle data in raw binary format.
- Character Streams: Manage data in the form of characters.
1. Byte Streams
- InputStream: InputStream reads byte data.
- OutputStream: OutputStream writes byte data.
InputStream
- AudioInputStream
- ByteArrayInputStream
- FileInputStream
- FilterInputStream
- StringBufferInputStream
- ObjectInputStream
1. How to Create an InputStream
// Here we are Creating an InputStream
InputStream obj = new FileInputStream();
2. Different Methods of InputStream
Method Name | Usage |
read() | It reads one byte of data from the input stream. |
read(byte[] array)() | It reads a byte from the stream and stores that byte in the specified array. |
mark() | Marks the position in the input stream until the data has been read. |
available() | It returns the number of bytes available in the input stream. |
markSupported() | Check if the mark() method and the reset() method is supported in the stream. |
reset() | It returns the control to the point where the mark was set inside the stream. |
skips() | It skips and removes a particular number of bytes from the input stream. |
close() | It closes the input stream. |
2. Output Stream
- ByteArrayOutputStream
- FileOutputStream
- StringBufferOutputStream
- ObjectOutputStream
- DataOutputStream
- PrintStream
1. How to create an OutputStream
// Creating an OutputStream
OutputStream obj = new FileOutputStream();
2. Different Methods of OutputStream
Method Name | Usage |
write() | It writes the specified byte to the output stream. |
write(byte[] array) | It writes the bytes inside a specific array of the output stream. |
close() | It closes the output stream. |
flush() | It forces to write all the data present in an output stream to the destination. |
2. Character Streams
- Reader: It reads character data.
- Writer: It produces character data.
Example
FileReader reader = new FileReader("input.txt");
int data = reader.read();
Core File Handling Classes in Java
Java has a number of classes that simplify file-handling procedures. These classes are found in the"java.io" and"java.nio.file"packages. there are three types of file-handling classes in Java they are as follows.- File Class
- FileReader and FileWriter
- BufferedReader and BufferedWriter
1. File Class
Example
File file = new File("example.txt");
if (file.exists()) {
System.out.println("File exists");
} else {
System.out.println("File does not exist");
}
Java File Class Methods
Method Name | Description | Return Type |
canRead() | It tests whether the file is readable or not. | Boolean |
canWrite() | It tests whether the file is writable or not. | Boolean |
createNewFile() | It creates an empty file. | Boolean |
delete() | It deletes a file. | Boolean |
exists() | It tests whether the file exists or not. | Boolean |
length() | Returns the size of the file in bytes. | Long |
getName() | Returns the name of the file. | String |
list() | Returns an array of the files in the directory. | String[] |
mkdir() | Creates a new directory. | Boolean |
getAbsolutePath() | Returns the absolute pathname of the file. | String |
2. FileReader and FileWriter
Example of writing data
FileWriter writer = new FileWriter("example.txt");
writer.write("Welcome to Scholarhat!");
writer.close();
Example of reading data:
FileReader reader = new FileReader("example.txt");
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
reader.close();
3. Buffered Reader and BufferedWriter
BufferedReader and BufferedWriter boost performance by buffering input and output streams. They are useful for managing huge files.
Example of reading data with a buffered reader
BufferedReader br = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println("Welcome to ScholarHat");
}
br.close();
Different Operations of File Handling in Java
1. Create File
File file = new File("newFile.txt");
if (file.createNewFile()) {
System.out.println("File created successfully.");
} else {
System.out.println("File already exists.");
}
2. Write File
You can write data to files using FileWriter or BufferedWriter:FileWriter writer = new FileWriter("example.txt");
writer.write("This is file content.");
writer.close();
3. Read File
Use FileReader or BufferedReader to read data from files:BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
Delete Files
You can delete a file using the delete() method of the File class:File file = new File("example.txt");
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete file.");
}
Advanced File Operations
- Copying and Moving Files
- File Attributes: Size, Path, and Permissions
1. Copying and Moving Files
Files.copy(Paths.get("source.txt"), Paths.get("destination.txt"));
Files.move(Paths.get("source.txt"), Paths.get("newLocation.txt"));
2. File attributes
File attributes include size, path, and permissions. The File class allows you to access file attributes like size, location, and permissions.File file = new File("example.txt");
System.out.println("File size: " + file.length() + " bytes");
System.out.println("File path: " + file.getAbsolutePath());
System.out.println("Is file writable? " + file.canWrite());
Working with Different File Formats
1. Text Files
Text files contain data in a human-readable format. To work with text files, use character streams (FileReader and FileWriter).2. Binary files
Binary files hold data in a binary format, which is commonly used for photos, movies, and generated code. To handle binary files, use byte streams (FileInputStream and FileOutputStream).3. CSV files
CSV (Comma-Separated Values) files are text files that store tabular data. BufferedReader and FileWriter allow you to read and write CSV files.Example of reading CSV data:
BufferedReader br = new BufferedReader(new FileReader("data.csv"));
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
System.out.println(Arrays.toString(values));
}
br.close();
Properties Files
Properties files are used to store configuration data. Java provides the Properties class for reading and writing key-value pairs.Properties props = new Properties();
props.load(new FileReader("config.properties"));
String value = props.getProperty("key");
System.out.println("Value: " + value);
Exception Handling in File Operations
File handling operations frequently throw checked exceptions, such as IOException or FileNotFoundException. To handle these exceptions, utilize a try-catch block.try {
FileReader reader = new FileReader("example.txt");
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
Conclusion
FAQs
- Reusability: File handling allows us to preserve the information/data generated after we run the program.
- Saves Time: Some programs might require a large amount of input from their users.
Take our Java skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.