Introduction
Java applications often need to store information beyond the lifetime of a program.
For example:
- A notes application can save notes to a text file.
- A student management application can store student records.
- A backend application can write logs to files.
- A configuration system can read settings from files.
- A desktop application can save user preferences.
Variables, arrays, and collections store data in memory while the application is running. When the application terminates, that in-memory data is normally lost.
Java provides several APIs for working with files and directories. The traditional java.io package contains classes such as File, FileReader, FileWriter, BufferedReader, and BufferedWriter. Modern Java applications also commonly use the NIO.2 API from java.nio.file, especially Path and Files.
In this tutorial, you will learn:
- What file handling is
- How to create and inspect files
- How to read text files
- How to write and append text
- How buffering improves file operations
- How to use
PathandFiles - How to handle file-related exceptions
- How Java serialization and deserialization work
- How to build practical file-handling projects
- File handling best practices
By the end of this tutorial, you should be able to build Java programs that create, read, write, update, and manage files safely.
Table of Contents
- What Is File Handling?
- Java File Handling Packages
- Creating a File
- Checking File Information
- Deleting a File
- Reading a Text File with FileReader
- Writing a File with FileWriter
- Appending Data to a File
- Reading Files with BufferedReader
- Writing Files with BufferedWriter
- FileReader vs BufferedReader
- Modern Java File Handling with Path and Files
- Copying and Moving Files
- Working with Directories
- Exception Handling
- Serialization
- Deserialization
- Serialization Best Practices and Security
- File Handling Best Practices
- Practical Projects
- Practice Exercises
- Summary
- SEO Keywords
What Is File Handling?
File handling is the process of creating, reading, writing, updating, copying, moving, and deleting files stored on a computer or other storage system.
Common file operations include:
- Create a file
- Read file contents
- Write data
- Append data
- Delete files
- Rename files
- Copy files
- Move files
- Create directories
- List directory contents
- Store application data
A simple file-handling workflow looks like this:
1Java Application 2 | 3 v 4 File/Path 5 | 6 v 7 Read / Write 8 | 9 v 10 Close Resource
The resource should be closed after the operation is completed. Java's try-with-resources statement is the preferred way to automatically close many file-related resources.
Java File Handling Packages
Traditional Java file handling is available through the java.io package.
1import java.io.*;
For modern file and directory operations, Java provides the NIO.2 API:
1import java.nio.file.*;
Important classes include:
| Class | Purpose |
|---|---|
File | Represents a file or directory |
FileReader | Reads character data |
FileWriter | Writes character data |
BufferedReader | Efficiently reads text |
BufferedWriter | Efficiently writes text |
Path | Represents a file or directory path |
Files | Provides modern file operations |
ObjectOutputStream | Serializes objects |
ObjectInputStream | Deserializes objects |
For new Java applications, learning Path and Files is strongly recommended.
Creating a File
The traditional File class can be used to create a new file.
1import java.io.File; 2import java.io.IOException; 3 4public class CreateFileExample { 5 6 public static void main(String[] args) { 7 File file = new File("notes.txt"); 8 9 try { 10 if (file.createNewFile()) { 11 System.out.println("File created successfully."); 12 } else { 13 System.out.println("File already exists."); 14 } 15 } catch (IOException e) { 16 System.err.println("Unable to create file: " + e.getMessage()); 17 } 18 } 19}
How This Code Works
1File file = new File("notes.txt");
This creates a File object representing notes.txt. It does not necessarily create the physical file immediately.
The actual file is created when:
1file.createNewFile();
is executed.
The method returns:
trueif a new file was createdfalseif the file already existed
Why Use try-with-resources?
For simple File creation, no resource needs to be closed manually. However, when working with readers, writers, or streams, prefer try-with-resources.
This prevents resource leaks and makes the code easier to maintain.
Checking File Information
The File class provides several methods for inspecting a file.
1import java.io.File; 2 3public class FileInformationExample { 4 5 public static void main(String[] args) { 6 File file = new File("notes.txt"); 7 8 if (!file.exists()) { 9 System.out.println("File does not exist."); 10 return; 11 } 12 13 System.out.println("Name: " + file.getName()); 14 System.out.println("Path: " + file.getPath()); 15 System.out.println("Absolute Path: " + file.getAbsolutePath()); 16 System.out.println("Size: " + file.length() + " bytes"); 17 System.out.println("Readable: " + file.canRead()); 18 System.out.println("Writable: " + file.canWrite()); 19 System.out.println("Directory: " + file.isDirectory()); 20 System.out.println("File: " + file.isFile()); 21 } 22}
Important Methods
exists()checks whether the path exists.getName()returns the file or directory name.getPath()returns the path used to construct the object.getAbsolutePath()returns the absolute path.length()returns the file size in bytes.canRead()checks whether the file can be read.canWrite()checks whether the file can be written.isFile()checks whether the path represents a regular file.isDirectory()checks whether the path represents a directory.
Deleting a File
A file can be deleted using File.delete().
1import java.io.File; 2 3public class DeleteFileExample { 4 5 public static void main(String[] args) { 6 File file = new File("notes.txt"); 7 8 if (!file.exists()) { 9 System.out.println("File does not exist."); 10 return; 11 } 12 13 if (file.delete()) { 14 System.out.println("File deleted successfully."); 15 } else { 16 System.out.println("Unable to delete the file."); 17 } 18 } 19}
Always check whether the file exists before attempting operations when that improves the application's error handling.
Reading a Text File with FileReader
FileReader is designed for reading character-based text files.
A simple example is:
1import java.io.FileReader; 2import java.io.IOException; 3 4public class FileReaderExample { 5 6 public static void main(String[] args) { 7 try (FileReader reader = new FileReader("notes.txt")) { 8 9 int character; 10 11 while ((character = reader.read()) != -1) { 12 System.out.print((char) character); 13 } 14 15 } catch (IOException e) { 16 System.err.println("Unable to read file: " + e.getMessage()); 17 } 18 } 19}
Understanding read()
The read() method returns an integer.
It returns:
- The character value when a character is available
-1when the end of the file is reached
This is why the following pattern is commonly used:
1int character; 2 3while ((character = reader.read()) != -1) { 4 System.out.print((char) character); 5}
For larger text files or line-based processing, BufferedReader is generally more convenient.
Writing a Text File with FileWriter
FileWriter can write character data to a text file.
1import java.io.FileWriter; 2import java.io.IOException; 3 4public class FileWriterExample { 5 6 public static void main(String[] args) { 7 8 try (FileWriter writer = new FileWriter("notes.txt")) { 9 10 writer.write("Welcome to Java File Handling."); 11 writer.write(System.lineSeparator()); 12 writer.write("This file was created by a Java program."); 13 14 System.out.println("File written successfully."); 15 16 } catch (IOException e) { 17 System.err.println("Unable to write file: " + e.getMessage()); 18 } 19 } 20}
Important Behavior
By default:
1new FileWriter("notes.txt")
writes to the file from the beginning and can overwrite existing content.
If you want to append instead, use:
1new FileWriter("notes.txt", true)
Appending Data to a File
Appending means adding new content to the end of an existing file without replacing its previous contents.
1import java.io.FileWriter; 2import java.io.IOException; 3 4public class AppendFileExample { 5 6 public static void main(String[] args) { 7 8 try (FileWriter writer = new FileWriter("notes.txt", true)) { 9 10 writer.write(System.lineSeparator()); 11 writer.write("New note added."); 12 13 System.out.println("Data appended successfully."); 14 15 } catch (IOException e) { 16 System.err.println("Unable to append data: " + e.getMessage()); 17 } 18 } 19}
The second argument:
1true
enables append mode.
Reading Files with BufferedReader
BufferedReader reads text efficiently and provides a convenient readLine() method.
1import java.io.BufferedReader; 2import java.io.FileReader; 3import java.io.IOException; 4 5public class BufferedReaderExample { 6 7 public static void main(String[] args) { 8 9 try (BufferedReader reader = 10 new BufferedReader(new FileReader("notes.txt"))) { 11 12 String line; 13 14 while ((line = reader.readLine()) != null) { 15 System.out.println(line); 16 } 17 18 } catch (IOException e) { 19 System.err.println("Unable to read file: " + e.getMessage()); 20 } 21 } 22}
Why Use BufferedReader?
Reading one character at a time can result in many underlying I/O operations.
BufferedReader maintains an internal buffer and provides efficient sequential text reading.
It is especially useful when processing a file line by line.
For example:
1while ((line = reader.readLine()) != null) { 2 process(line); 3}
This pattern is common in log processing, configuration parsing, and text-file processing.
Writing Files with BufferedWriter
BufferedWriter provides efficient character output with buffering.
1import java.io.BufferedWriter; 2import java.io.FileWriter; 3import java.io.IOException; 4 5public class BufferedWriterExample { 6 7 public static void main(String[] args) { 8 9 try (BufferedWriter writer = 10 new BufferedWriter(new FileWriter("notes.txt"))) { 11 12 writer.write("Java Programming"); 13 writer.newLine(); 14 15 writer.write("File Handling Tutorial"); 16 writer.newLine(); 17 18 writer.write("BufferedWriter example"); 19 20 System.out.println("Data written successfully."); 21 22 } catch (IOException e) { 23 System.err.println("Unable to write file: " + e.getMessage()); 24 } 25 } 26}
newLine() vs "\n"
Prefer:
1writer.newLine();
when writing platform-independent text because it uses the appropriate line separator for the current operating system.
FileReader vs BufferedReader
| Feature | FileReader | BufferedReader |
|---|---|---|
| Reads character data | Yes | Yes |
| Reads complete lines | No | Yes |
| Uses buffering | No direct buffering | Yes |
| Convenient for line processing | No | Yes |
| Suitable for simple reading | Yes | Yes |
| Better choice for large text processing | Usually no | Usually yes |
A common combination is:
1BufferedReader reader = 2 new BufferedReader(new FileReader("notes.txt"));
The FileReader provides the underlying character stream while BufferedReader adds buffering and line-oriented operations.
Modern Java File Handling with Path and Files
Modern Java applications should also learn the NIO.2 file API.
The most important classes are:
1Path 2Files
Example:
1import java.io.IOException; 2import java.nio.file.Files; 3import java.nio.file.Path; 4 5public class ModernFileExample { 6 7 public static void main(String[] args) { 8 9 Path path = Path.of("notes.txt"); 10 11 try { 12 Files.writeString( 13 path, 14 "Welcome to modern Java file handling." 15 ); 16 17 String content = Files.readString(path); 18 19 System.out.println(content); 20 21 } catch (IOException e) { 22 System.err.println("File operation failed: " + e.getMessage()); 23 } 24 } 25}
This approach is concise and is often easier to maintain than manually combining older I/O classes.
Creating a File with Files
1import java.io.IOException; 2import java.nio.file.Files; 3import java.nio.file.Path; 4 5public class CreateFileWithFiles { 6 7 public static void main(String[] args) { 8 9 Path path = Path.of("data", "notes.txt"); 10 11 try { 12 Files.createDirectories(path.getParent()); 13 14 if (Files.notExists(path)) { 15 Files.createFile(path); 16 System.out.println("File created."); 17 } else { 18 System.out.println("File already exists."); 19 } 20 21 } catch (IOException e) { 22 System.err.println("Unable to create file: " + e.getMessage()); 23 } 24 } 25}
Writing with Files.writeString()
1import java.io.IOException; 2import java.nio.file.Files; 3import java.nio.file.Path; 4 5public class WriteStringExample { 6 7 public static void main(String[] args) { 8 9 Path path = Path.of("notes.txt"); 10 11 try { 12 Files.writeString( 13 path, 14 "Java makes file handling easier with NIO.2." 15 ); 16 17 System.out.println("Content saved."); 18 19 } catch (IOException e) { 20 System.err.println("Unable to save content: " + e.getMessage()); 21 } 22 } 23}
Reading with Files.readString()
1import java.io.IOException; 2import java.nio.file.Files; 3import java.nio.file.Path; 4 5public class ReadStringExample { 6 7 public static void main(String[] args) { 8 9 Path path = Path.of("notes.txt"); 10 11 try { 12 String content = Files.readString(path); 13 14 System.out.println(content); 15 16 } catch (IOException e) { 17 System.err.println("Unable to read file: " + e.getMessage()); 18 } 19 } 20}
For very large files, avoid loading the entire file into memory with readString(). Use buffered or streaming approaches when appropriate.
Copying Files
The NIO.2 API provides a convenient way to copy files.
1import java.io.IOException; 2import java.nio.file.Files; 3import java.nio.file.Path; 4import java.nio.file.StandardCopyOption; 5 6public class CopyFileExample { 7 8 public static void main(String[] args) { 9 10 Path source = Path.of("notes.txt"); 11 Path target = Path.of("backup-notes.txt"); 12 13 try { 14 Files.copy( 15 source, 16 target, 17 StandardCopyOption.REPLACE_EXISTING 18 ); 19 20 System.out.println("File copied successfully."); 21 22 } catch (IOException e) { 23 System.err.println("Copy operation failed: " + e.getMessage()); 24 } 25 } 26}
REPLACE_EXISTING allows the destination file to be replaced if it already exists.
Moving and Renaming Files
Moving a file is also straightforward.
1import java.io.IOException; 2import java.nio.file.Files; 3import java.nio.file.Path; 4import java.nio.file.StandardCopyOption; 5 6public class MoveFileExample { 7 8 public static void main(String[] args) { 9 10 Path source = Path.of("notes.txt"); 11 Path target = Path.of("archive", "notes.txt"); 12 13 try { 14 Files.createDirectories(target.getParent()); 15 16 Files.move( 17 source, 18 target, 19 StandardCopyOption.REPLACE_EXISTING 20 ); 21 22 System.out.println("File moved successfully."); 23 24 } catch (IOException e) { 25 System.err.println("Move operation failed: " + e.getMessage()); 26 } 27 } 28}
A move operation can also be used to rename a file by changing its filename in the target path.
Working with Directories
Java can create directories using Files.createDirectories().
1import java.io.IOException; 2import java.nio.file.Files; 3import java.nio.file.Path; 4 5public class DirectoryExample { 6 7 public static void main(String[] args) { 8 9 Path directory = Path.of("data", "students", "records"); 10 11 try { 12 Files.createDirectories(directory); 13 14 System.out.println( 15 "Directory created: " + directory.toAbsolutePath() 16 ); 17 18 } catch (IOException e) { 19 System.err.println( 20 "Unable to create directory: " + e.getMessage() 21 ); 22 } 23 } 24}
createDirectories() creates missing parent directories as necessary.
For example:
1data/ 2└── students/ 3 └── records/
can be created in one operation.
Listing Directory Contents
You can use Files.list() to inspect the contents of a directory.
1import java.io.IOException; 2import java.nio.file.Files; 3import java.nio.file.Path; 4import java.util.stream.Stream; 5 6public class DirectoryListingExample { 7 8 public static void main(String[] args) { 9 10 Path directory = Path.of("data"); 11 12 try (Stream<Path> paths = Files.list(directory)) { 13 14 paths.forEach(path -> 15 System.out.println(path.getFileName()) 16 ); 17 18 } catch (IOException e) { 19 System.err.println( 20 "Unable to list directory: " + e.getMessage() 21 ); 22 } 23 } 24}
Notice that Files.list() returns a stream that should also be closed. This is why it is placed inside try-with-resources.
File Handling Flow
A reliable file operation generally follows this pattern:
1Validate Path 2 | 3 v 4Open Resource 5 | 6 v 7Read / Write 8 | 9 v 10Handle Errors 11 | 12 v 13Close Resource
With try-with-resources, resource cleanup is handled automatically.
Example:
1try (BufferedReader reader = Files.newBufferedReader(path)) { 2 String line; 3 4 while ((line = reader.readLine()) != null) { 5 System.out.println(line); 6 } 7} catch (IOException e) { 8 System.err.println("File operation failed: " + e.getMessage()); 9}
Exception Handling in File Operations
File operations can fail for many reasons:
- The file does not exist.
- The application does not have permission.
- A directory is used where a file is expected.
- The storage device has an I/O problem.
- The path is invalid.
- The file is unavailable during the operation.
The most common exception is:
1IOException
Example:
1try { 2 String content = Files.readString(Path.of("notes.txt")); 3 System.out.println(content); 4} catch (IOException e) { 5 System.err.println("Could not read notes.txt."); 6}
Common File-Related Exceptions
| Exception | Description |
|---|---|
IOException | General input/output failure |
FileNotFoundException | File cannot be opened or found |
EOFException | Unexpected end of input |
InvalidClassException | Serialization class incompatibility |
NotSerializableException | Object cannot be serialized |
Avoid exposing internal filesystem details to end users when those details could reveal sensitive information.
Serialization
Serialization converts a Java object's state into a byte stream that can be stored or transmitted.
A serializable class implements:
1Serializable
Example:
1import java.io.Serializable; 2 3public class Student implements Serializable { 4 5 private static final long serialVersionUID = 1L; 6 7 private final String name; 8 private final int marks; 9 10 public Student(String name, int marks) { 11 this.name = name; 12 this.marks = marks; 13 } 14 15 public String getName() { 16 return name; 17 } 18 19 public int getMarks() { 20 return marks; 21 } 22}
Why Use serialVersionUID?
A serialVersionUID is used during Java serialization to help determine whether the serialized object is compatible with the current class definition.
Explicitly declaring it makes the intended serialization version easier to control.
Serializing an Object
Use ObjectOutputStream to serialize an object.
1import java.io.FileOutputStream; 2import java.io.IOException; 3import java.io.ObjectOutputStream; 4 5public class SerializeExample { 6 7 public static void main(String[] args) { 8 9 Student student = new Student("Ankit", 95); 10 11 try (ObjectOutputStream output = 12 new ObjectOutputStream( 13 new FileOutputStream("student.ser"))) { 14 15 output.writeObject(student); 16 17 System.out.println("Student saved successfully."); 18 19 } catch (IOException e) { 20 System.err.println( 21 "Unable to save student: " + e.getMessage() 22 ); 23 } 24 } 25}
The serialized data is stored in:
1student.ser
Output
1Student saved successfully.
Deserialization
Deserialization is the process of reconstructing an object from a serialized byte stream.
ObjectInputStream is commonly used for this purpose.
1import java.io.FileInputStream; 2import java.io.IOException; 3import java.io.ObjectInputStream; 4 5public class DeserializeExample { 6 7 public static void main(String[] args) { 8 9 try (ObjectInputStream input = 10 new ObjectInputStream( 11 new FileInputStream("student.ser"))) { 12 13 Student student = (Student) input.readObject(); 14 15 System.out.println("Name: " + student.getName()); 16 System.out.println("Marks: " + student.getMarks()); 17 18 } catch (IOException | ClassNotFoundException e) { 19 System.err.println( 20 "Unable to load student: " + e.getMessage() 21 ); 22 } 23 } 24}
Output
1Name: Ankit 2Marks: 95
Serialization Security
Java native deserialization requires special care when the serialized data comes from an untrusted source.
Do not blindly deserialize arbitrary data received from:
- HTTP requests
- Uploaded files
- External users
- Untrusted network sources
- Unknown third-party systems
For data exchange between independent applications, formats such as JSON are often a better choice.
For example, a REST API commonly exchanges data using JSON rather than Java native serialization.
Serialization is useful in specific Java-to-Java scenarios, but it should not automatically be the first choice for application data persistence.
File Handling Best Practices
Follow these practices when writing production-quality Java file-handling code.
Use try-with-resources
Prefer:
1try (BufferedReader reader = Files.newBufferedReader(path)) { 2 // Read file 3}
instead of manually closing the reader.
Prefer Path and Files for Modern Applications
For new applications, become familiar with:
1Path 2Files
They provide a modern API for file and directory operations.
Validate Paths
Do not blindly trust paths supplied by users.
For applications that accept filenames or paths from users, validate them carefully and restrict access to intended directories when necessary.
Handle Exceptions Meaningfully
Avoid:
1catch (IOException e) { 2 System.out.println(e.getMessage()); 3}
when more useful context can be provided.
Prefer:
1catch (IOException e) { 2 System.err.println( 3 "Unable to save the configuration file: " 4 + e.getMessage() 5 ); 6}
Do Not Load Huge Files into Memory
This is convenient:
1String content = Files.readString(path);
but it loads the entire file into memory.
For large files, process the data incrementally.
For example:
1try (BufferedReader reader = Files.newBufferedReader(path)) { 2 3 String line; 4 5 while ((line = reader.readLine()) != null) { 6 process(line); 7 } 8 9} catch (IOException e) { 10 System.err.println("Unable to process file."); 11}
Use Appropriate Data Formats
Use the right storage technology for the problem.
For example:
- Plain text for simple text data
- JSON for interoperable structured data
- CSV for tabular data
- Databases for relational application data
- Object serialization only when its specific characteristics are appropriate
Practical Project: Notes Application
A simple notes application can append notes to a file.
1import java.io.BufferedWriter; 2import java.io.IOException; 3import java.nio.file.Files; 4import java.nio.file.Path; 5import java.nio.file.StandardOpenOption; 6 7public class NotesApp { 8 9 private static final Path NOTES_FILE = Path.of("notes.txt"); 10 11 public static void saveNote(String note) throws IOException { 12 13 if (note == null || note.isBlank()) { 14 throw new IllegalArgumentException( 15 "Note cannot be empty." 16 ); 17 } 18 19 try (BufferedWriter writer = Files.newBufferedWriter( 20 NOTES_FILE, 21 StandardOpenOption.CREATE, 22 StandardOpenOption.APPEND 23 )) { 24 25 writer.write(note); 26 writer.newLine(); 27 } 28 } 29 30 public static void main(String[] args) { 31 32 try { 33 saveNote("Learn Java Collections"); 34 saveNote("Practice Java File Handling"); 35 36 System.out.println("Notes saved successfully."); 37 38 } catch (IOException e) { 39 System.err.println( 40 "Unable to save notes: " + e.getMessage() 41 ); 42 } 43 } 44}
Why This Is Better
This example demonstrates several production-friendly concepts:
Pathinstead of manually constructing file pathsFiles.newBufferedWriter()try-with-resourcesCREATEto create the file when necessaryAPPENDto preserve existing notes- Input validation
- Meaningful exception handling
- Reusable
saveNote()method
Practical Project: Student Records
A simple student-record application can store structured information.
For learning purposes, Java serialization can demonstrate object persistence.
1import java.io.IOException; 2import java.io.ObjectOutputStream; 3import java.io.Serializable; 4import java.nio.file.Files; 5import java.nio.file.Path; 6 7class StudentRecord implements Serializable { 8 9 private static final long serialVersionUID = 1L; 10 11 private final String name; 12 private final int marks; 13 14 public StudentRecord(String name, int marks) { 15 if (name == null || name.isBlank()) { 16 throw new IllegalArgumentException( 17 "Student name cannot be empty." 18 ); 19 } 20 21 if (marks < 0 || marks > 100) { 22 throw new IllegalArgumentException( 23 "Marks must be between 0 and 100." 24 ); 25 } 26 27 this.name = name; 28 this.marks = marks; 29 } 30 31 public String getName() { 32 return name; 33 } 34 35 public int getMarks() { 36 return marks; 37 } 38} 39 40public class StudentDatabase { 41 42 public static void main(String[] args) { 43 44 Path file = Path.of("student.dat"); 45 46 StudentRecord student = 47 new StudentRecord("Ankit", 95); 48 49 try (ObjectOutputStream output = 50 new ObjectOutputStream( 51 Files.newOutputStream(file))) { 52 53 output.writeObject(student); 54 55 System.out.println( 56 "Student record saved successfully." 57 ); 58 59 } catch (IOException e) { 60 System.err.println( 61 "Unable to save student: " + e.getMessage() 62 ); 63 } 64 } 65}
Output
1Student record saved successfully.
For a real production application, consider whether a database or an interoperable format such as JSON would be more appropriate than Java native serialization.
Practical Project: File Copier
A file-copy utility is a useful project for understanding file operations.
1import java.io.IOException; 2import java.nio.file.Files; 3import java.nio.file.Path; 4import java.nio.file.StandardCopyOption; 5 6public class FileCopier { 7 8 public static void copy(Path source, Path target) 9 throws IOException { 10 11 if (Files.notExists(source)) { 12 throw new IOException( 13 "Source file does not exist: " + source 14 ); 15 } 16 17 if (!Files.isRegularFile(source)) { 18 throw new IOException( 19 "Source is not a regular file: " + source 20 ); 21 } 22 23 Files.copy( 24 source, 25 target, 26 StandardCopyOption.REPLACE_EXISTING 27 ); 28 } 29 30 public static void main(String[] args) { 31 32 Path source = Path.of("notes.txt"); 33 Path target = Path.of("backup-notes.txt"); 34 35 try { 36 copy(source, target); 37 38 System.out.println( 39 "File copied successfully." 40 ); 41 42 } catch (IOException e) { 43 System.err.println( 44 "Copy failed: " + e.getMessage() 45 ); 46 } 47 } 48}
Practice Exercises
Exercise 1: Diary Application
Create a diary application that:
- Accepts a diary entry from the user
- Appends the entry to a file
- Displays previous entries
- Uses
BufferedReaderorFiles - Handles
IOException - Prevents empty entries
Exercise 2: Employee Records
Create an employee-record application that stores:
- Employee name
- Employee ID
- Department
- Salary
Save the records to a file and load them when the program starts.
Exercise 3: File Copier
Create a program that:
- Accepts a source file
- Accepts a destination file
- Checks whether the source exists
- Copies the file
- Handles errors gracefully
Exercise 4: Student Result Manager
Create a program that:
- Reads student marks from a file
- Calculates the average
- Finds the highest mark
- Finds the lowest mark
- Writes the result to another file
Exercise 5: Log Analyzer
Create a log analyzer that:
- Reads a large log file line by line
- Counts error messages
- Counts warning messages
- Displays the total number of processed lines
- Avoids loading the entire file into memory
Exercise 6: Library Management System
Build a small library application that:
- Stores book information
- Adds new books
- Searches for books
- Saves records to persistent storage
- Loads records when the application starts
- Handles invalid input
- Handles file-related exceptions
Modern Java Note
The traditional java.io classes remain important because they are widely used and form an essential part of Java's I/O ecosystem.
However, modern Java developers should also understand NIO.2:
1java.nio.file
Important APIs include:
1Path 2Files 3StandardOpenOption 4StandardCopyOption
These APIs make many common file operations concise and provide powerful functionality for:
- File creation
- File reading
- File writing
- File copying
- File moving
- File deletion
- Directory creation
- Directory traversal
- File metadata
- Symbolic links
- File-system operations
A good learning path is:
1File 2 ↓ 3FileReader / FileWriter 4 ↓ 5BufferedReader / BufferedWriter 6 ↓ 7Path / Files 8 ↓ 9Streams and Directory Operations 10 ↓ 11Advanced I/O
Summary
In this Java File Handling tutorial, you learned how Java applications work with files and directories.
You learned:
- What file handling means
- How to create files using
File - How to inspect file information
- How to delete files
- How to read text with
FileReader - How to write text with
FileWriter - How to append data
- How
BufferedReaderimproves text reading - How
BufferedWriterimproves text writing - The difference between
FileReaderandBufferedReader - How to use modern
PathandFilesAPIs - How to copy and move files
- How to create and inspect directories
- How to handle
IOException - How Java serialization works
- How deserialization works
- Why untrusted Java deserialization can be dangerous
- File handling best practices
- How to build practical file-handling projects
File handling is an important Java skill because applications frequently need persistent data, configuration files, logs, reports, imports, exports, and local storage.
After learning file handling, useful next Java topics include Streams, Lambda Expressions, Collections, Multithreading, Concurrency, and Functional Programming.