Java File Handling
File handling connects Java code to data stored outside the running program. A path describes where the data belongs; reading or writing is a separate action that can fail. The examples distinguish text, bytes, directories, and resource cleanup.
Applications often need to store information outside the program's memory. For example, an application may need to save:
- User information
- Application logs
- Configuration settings
- Reports
- Text documents
- Transaction records
- Exported data
Java provides several classes and APIs for working with files and directories.
The most commonly used classes are available in the java.io and java.nio.file packages.
1. What is File Handling?
File handling refers to performing operations on files and directories using a program.
Common file operations include:
- Creating a file
- Checking whether a file exists
- Writing data to a file
- Reading data from a file
- Appending data
- Copying a file
- Moving or renaming a file
- Deleting a file
- Creating directories
- Listing files in a directory
Java provides different classes for these operations.
2. Java File Handling Packages
Two important packages are:
java.ioand
java.nio.fileThe java.io package provides traditional file-handling classes such as:
FileFileReaderFileWriterBufferedReaderBufferedWriterFileInputStreamFileOutputStreamPrintWriter
The newer NIO API provides classes such as:
PathPathsFiles
For many modern file operations, the java.nio.file.Files API is convenient and powerful.
3. The File Class
The File class is available in:
java.io.FileIt represents a file or directory pathname.
Import it using:
import java.io.File;A File object does not itself contain the file's data. It represents the location or pathname of a file or directory.
4. Creating a File Object
Example
import java.io.File;
public class HelloWorld {
public static void main(String[] args) {
File file = new File("example.txt");
System.out.println(file);
}
}Output
example.txtHere:
new File("example.txt")creates a File object representing the path.
It does not necessarily create the physical file.
5. Creating a New File
To physically create a file, use the createNewFile() method.
Example
import java.io.File;
import java.io.IOException;
public class HelloWorld {
public static void main(String[] args) {
File file = new File("example.txt");
try {
if (file.createNewFile()) {
System.out.println("File created successfully.");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
}
}
}Possible Output
If the file does not already exist:
File created successfully.If it already exists:
File already exists.6. Why Does createNewFile() Throw an Exception?
File operations can fail because of several reasons, such as:
- Invalid path
- Permission problems
- Storage problems
- I/O errors
Therefore, Java requires the possible IOException to be handled or declared.
For example:
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}7. Checking Whether a File Exists
The exists() method checks whether the specified file or directory exists.
Example
import java.io.File;
public class HelloWorld {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.exists()) {
System.out.println("File exists.");
} else {
System.out.println("File does not exist.");
}
}
}Output
File exists.8. Getting the File Name
The getName() method returns the name of the file or directory represented by the File object.
import java.io.File;
public class HelloWorld {
public static void main(String[] args) {
File file = new File("documents/report.txt");
System.out.println("File name: " + file.getName());
}
}Output
File name: report.txt9. Getting the File Path
The getPath() method returns the pathname used to create the File object.
import java.io.File;
public class HelloWorld {
public static void main(String[] args) {
File file = new File("documents/report.txt");
System.out.println(file.getPath());
}
}Output
documents/report.txt10. Getting the Absolute Path
The getAbsolutePath() method returns the absolute path of the file.
import java.io.File;
public class HelloWorld {
public static void main(String[] args) {
File file = new File("example.txt");
System.out.println(file.getAbsolutePath());
}
}The exact output depends on the computer and the program's working directory.
For example:
C:\Projects\JavaApp\example.txt11. Checking Whether It Is a File
The isFile() method checks whether the path represents a file.
import java.io.File;
public class HelloWorld {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.isFile()) {
System.out.println("It is a file.");
}
}
}12. Checking Whether It Is a Directory
The isDirectory() method checks whether the path represents a directory.
import java.io.File;
public class HelloWorld {
public static void main(String[] args) {
File file = new File("documents");
if (file.isDirectory()) {
System.out.println("It is a directory.");
}
}
}13. Creating a Directory
The mkdir() method creates a directory.
import java.io.File;
public class HelloWorld {
public static void main(String[] args) {
File directory = new File("documents");
if (directory.mkdir()) {
System.out.println("Directory created.");
} else {
System.out.println("Directory could not be created.");
}
}
}Output
Directory created.If the directory already exists, the method returns false.
14. Creating Multiple Directories
The mkdirs() method can create multiple missing directories in a path.
For example:
project
|
└── reports
|
└── yearlyExample
import java.io.File;
public class HelloWorld {
public static void main(String[] args) {
File directory = new File("project/reports/yearly");
if (directory.mkdirs()) {
System.out.println("Directories created.");
} else {
System.out.println("Directories already exist or could not be created.");
}
}
}Difference Between mkdir() and mkdirs()
| Method | Purpose |
|---|---|
mkdir() | Creates one directory |
mkdirs() | Creates the required parent directories as well |
15. Writing Data to a File
The FileWriter class can be used to write character data into a file.
Import it using:
import java.io.FileWriter;Example
import java.io.FileWriter;
import java.io.IOException;
public class HelloWorld {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello Java!");
writer.close();
System.out.println("Data written successfully.");
} catch (IOException e) {
System.out.println("An error occurred.");
}
}
}Output
Data written successfully.The file will contain:
Hello Java!16. Writing Multiple Lines
You can write multiple lines using \n.
import java.io.FileWriter;
import java.io.IOException;
public class HelloWorld {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("student.txt");
writer.write("Name: Rahul\n");
writer.write("Age: 22\n");
writer.write("Course: Java");
writer.close();
System.out.println("Student information saved.");
} catch (IOException e) {
System.out.println("Error while writing file.");
}
}
}The file contains:
Name: Rahul
Age: 22
Course: Java17. Overwriting vs Appending
By default:
new FileWriter("example.txt")opens the file for writing and can replace its existing contents.
If you want to append data to the existing content, use:
new FileWriter("example.txt", true)The second parameter indicates append mode.
Example
import java.io.FileWriter;
import java.io.IOException;
public class HelloWorld {
public static void main(String[] args) {
try {
FileWriter writer =
new FileWriter("example.txt", true);
writer.write("\nNew line added.");
writer.close();
System.out.println("Data appended.");
} catch (IOException e) {
System.out.println("Error occurred.");
}
}
}18. Reading a File Using FileReader
The FileReader class is used to read character data from a file.
Example
import java.io.FileReader;
import java.io.IOException;
public class HelloWorld {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("example.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
System.out.println("Error while reading file.");
}
}
}Suppose example.txt contains:
Hello Java!Output
Hello Java!19. Understanding read()
The read() method reads one character at a time.
For example:
int character = reader.read();It returns:
- The character value if data is available.
-1when the end of the file is reached.
That is why we commonly write:
while ((character = reader.read()) != -1)20. Reading a File Using BufferedReader
Reading one character at a time may not be the most convenient approach for text files.
BufferedReader provides convenient line-based reading.
Example
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class HelloWorld {
public static void main(String[] args) {
try {
BufferedReader reader =
new BufferedReader(
new FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
System.out.println("Error while reading file.");
}
}
}21. Reading All Lines Using Files.readAllLines()
The NIO API provides a simpler approach for many small text files.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class HelloWorld {
public static void main(String[] args) {
Path path = Path.of("example.txt");
try {
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error while reading file.");
}
}
}This is convenient when the complete file can reasonably be loaded into memory.
22. Writing Using Files.writeString()
The NIO API also provides Files.writeString() for writing text.
Example
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class HelloWorld {
public static void main(String[] args) {
Path path = Path.of("example.txt");
try {
Files.writeString(path, "Hello from Java File Handling!");
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("Error while writing file.");
}
}
}23. Reading Using Files.readString()
For a text file whose contents can reasonably be loaded into memory:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class HelloWorld {
public static void main(String[] args) {
Path path = Path.of("example.txt");
try {
String content = Files.readString(path);
System.out.println(content);
} catch (IOException e) {
System.out.println("Error while reading file.");
}
}
}24. Appending Using Files.writeString()
You can append content using StandardOpenOption.APPEND.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class HelloWorld {
public static void main(String[] args) {
Path path = Path.of("example.txt");
try {
Files.writeString(
path,
"\nNew content added.",
StandardOpenOption.CREATE,
StandardOpenOption.APPEND
);
System.out.println("Content appended.");
} catch (IOException e) {
System.out.println("Error while appending.");
}
}
}25. Deleting a File
The delete() method of the File class can delete a file or an empty directory.
Example
import java.io.File;
public class HelloWorld {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.delete()) {
System.out.println("File deleted.");
} else {
System.out.println("File could not be deleted.");
}
}
}26. Deleting Using Files.delete()
The NIO API provides another approach.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class HelloWorld {
public static void main(String[] args) {
Path path = Path.of("example.txt");
try {
Files.delete(path);
System.out.println("File deleted.");
} catch (IOException e) {
System.out.println("Unable to delete file.");
}
}
}Files.deleteIfExists() can be useful when you do not want an exception simply because the file is missing.
Files.deleteIfExists(path);27. Copying a File
The Files.copy() method can copy a file.
Example
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class HelloWorld {
public static void main(String[] args) {
Path source = Path.of("example.txt");
Path destination = Path.of("backup.txt");
try {
Files.copy(source, destination);
System.out.println("File copied successfully.");
} catch (IOException e) {
System.out.println("Error while copying file.");
}
}
}28. Moving or Renaming a File
The Files.move() method can be used to move a file or rename it.
Example
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class HelloWorld {
public static void main(String[] args) {
Path source = Path.of("example.txt");
Path destination = Path.of("new-example.txt");
try {
Files.move(source, destination);
System.out.println("File moved or renamed.");
} catch (IOException e) {
System.out.println("Error while moving file.");
}
}
}If the destination is in the same directory, this can effectively rename the file.
29. Listing Files in a Directory
The File class provides the listFiles() method.
Example
import java.io.File;
public class HelloWorld {
public static void main(String[] args) {
File directory = new File("documents");
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
System.out.println(file.getName());
}
}
}
}This prints the files and directories contained in the documents directory.
30. Checking File Properties
The File class provides several useful methods.
Example
import java.io.File;
public class HelloWorld {
public static void main(String[] args) {
File file = new File("example.txt");
System.out.println("Exists: " + file.exists());
System.out.println("Is File: " + file.isFile());
System.out.println("Is Directory: " + file.isDirectory());
System.out.println("Name: " + file.getName());
System.out.println("Path: " + file.getPath());
System.out.println("Absolute Path: " + file.getAbsolutePath());
System.out.println("Size: " + file.length() + " bytes");
}
}Possible output:
Exists: true
Is File: true
Is Directory: false
Name: example.txt
Path: example.txt
Absolute Path: C:\Projects\JavaApp\example.txt
Size: 25 bytesThe exact absolute path and file size depend on the system and file contents.
31. Byte Streams vs Character Streams
Java provides different stream types for different kinds of data.
Character Streams
Character streams are generally used for text data.
Examples:
FileReader
FileWriter
BufferedReader
BufferedWriterByte Streams
Byte streams are used for binary data.
Examples:
FileInputStream
FileOutputStreamBinary files can include:
- Images
- Audio
- Video
- PDF files
- Other binary data
32. FileInputStream
FileInputStream reads raw bytes from a file.
Example
import java.io.FileInputStream;
import java.io.IOException;
public class HelloWorld {
public static void main(String[] args) {
try {
FileInputStream input =
new FileInputStream("data.txt");
int data;
while ((data = input.read()) != -1) {
System.out.print((char) data);
}
input.close();
} catch (IOException e) {
System.out.println("Error while reading.");
}
}
}33. FileOutputStream
FileOutputStream writes bytes to a file.
Example
import java.io.FileOutputStream;
import java.io.IOException;
public class HelloWorld {
public static void main(String[] args) {
try {
FileOutputStream output =
new FileOutputStream("data.txt");
String message = "Hello Java";
output.write(message.getBytes());
output.close();
System.out.println("Data written.");
} catch (IOException e) {
System.out.println("Error while writing.");
}
}
}34. BufferedWriter
BufferedWriter can be used to efficiently write character data.
Example
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class HelloWorld {
public static void main(String[] args) {
try {
BufferedWriter writer =
new BufferedWriter(
new FileWriter("example.txt"));
writer.write("Java File Handling");
writer.newLine();
writer.write("BufferedWriter example");
writer.close();
System.out.println("Data written.");
} catch (IOException e) {
System.out.println("Error while writing.");
}
}
}35. Try-With-Resources
Java provides try-with-resources to automatically close resources.
Instead of:
FileReader reader = new FileReader("example.txt");
try {
// read file
} finally {
reader.close();
}you can write:
try (FileReader reader = new FileReader("example.txt")) {
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
System.out.println("Error while reading.");
}When the try block finishes, Java automatically closes the resource.
This is generally preferable when working with resources that implement AutoCloseable.
36. Try-With-Resources with BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class HelloWorld {
public static void main(String[] args) {
try (BufferedReader reader =
new BufferedReader(
new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error while reading file.");
}
}
}There is no explicit:
reader.close();because try-with-resources handles it automatically.
37. Handling IOException
File operations can produce I/O errors.
A common approach is:
try {
// file operation
} catch (IOException e) {
System.out.println("File operation failed.");
}You can also print the exception information:
catch (IOException e) {
e.printStackTrace();
}For production applications, error handling should be designed according to the application's requirements rather than simply printing stack traces.
38. File vs Path
Java provides both traditional File APIs and the newer NIO Path/Files APIs.
File
File file = new File("example.txt");Path
Path path = Path.of("example.txt");The NIO API provides many useful operations through Files:
Files.exists(path);
Files.createFile(path);
Files.readString(path);
Files.writeString(path, "Hello");
Files.copy(source, destination);
Files.move(source, destination);
Files.delete(path);39. Practical Example: Create and Write a Student Report
The following example combines several file operations.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class HelloWorld {
public static void main(String[] args) {
Path path = Path.of("student-report.txt");
String report =
"Student Report\n" +
"--------------\n" +
"Name: Rahul\n" +
"Course: Java\n" +
"Score: 85";
try {
Files.writeString(path, report);
System.out.println("Report created successfully.");
String content = Files.readString(path);
System.out.println("\nReport Content:");
System.out.println(content);
} catch (IOException e) {
System.out.println("Error processing report.");
}
}
}Output
Report created successfully.
Report Content:
Student Report
--------------
Name: Rahul
Course: Java
Score: 8540. Practical Example: File Backup
Suppose an application needs to create a backup of a text file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class HelloWorld {
public static void main(String[] args) {
Path source = Path.of("student-report.txt");
Path backup = Path.of("student-report-backup.txt");
try {
Files.copy(source, backup);
System.out.println("Backup created successfully.");
} catch (IOException e) {
System.out.println("Backup failed.");
}
}
}41. Practical Example: Simple Log File
Applications often store events in log files.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class HelloWorld {
public static void main(String[] args) {
Path logFile = Path.of("application.log");
try {
Files.writeString(
logFile,
"Application started.\n",
StandardOpenOption.CREATE,
StandardOpenOption.APPEND
);
Files.writeString(
logFile,
"User logged in.\n",
StandardOpenOption.APPEND
);
System.out.println("Log entries added.");
} catch (IOException e) {
System.out.println("Unable to write log.");
}
}
}The file may contain:
Application started.
User logged in.42. Common File Handling Mistakes
Mistake 1: Forgetting to Close a Resource
Avoid leaving resources open unnecessarily.
Prefer:
try (BufferedReader reader =
new BufferedReader(new FileReader("example.txt"))) {
// read data
} catch (IOException e) {
// handle exception
}Mistake 2: Assuming new File() Creates a File
This:
File file = new File("example.txt");only creates a File object representing the path.
It does not necessarily create the physical file.
To create the file:
file.createNewFile();Mistake 3: Using the Wrong Path
A relative path such as:
"example.txt"is interpreted relative to the program's working directory.
When debugging file-location issues, check:
file.getAbsolutePath();Mistake 4: Overwriting Data Accidentally
This:
new FileWriter("example.txt")can overwrite existing text.
For appending:
new FileWriter("example.txt", true)or use the appropriate Files.writeString() options.
Mistake 5: Forgetting Exception Handling
Many file operations can throw IOException.
Therefore, handle it appropriately:
try {
// file operation
} catch (IOException e) {
// handle error
}43. Commonly Used File Handling Classes
| Class | Purpose |
|---|---|
File | Represents a file or directory path |
FileReader | Reads character data |
FileWriter | Writes character data |
BufferedReader | Efficiently reads text, especially line by line |
BufferedWriter | Efficiently writes character data |
FileInputStream | Reads bytes |
FileOutputStream | Writes bytes |
PrintWriter | Convenient text output |
Path | Represents a file-system path |
Files | Provides many file-system operations |
44. Commonly Used File Methods
| Method | Purpose |
|---|---|
exists() | Checks whether path exists |
createNewFile() | Creates a new file |
delete() | Deletes a file or empty directory |
getName() | Returns file/directory name |
getPath() | Returns pathname |
getAbsolutePath() | Returns absolute pathname |
isFile() | Checks whether path represents a file |
isDirectory() | Checks whether path represents a directory |
length() | Returns file size in bytes |
mkdir() | Creates a directory |
mkdirs() | Creates directories including missing parents |
listFiles() | Returns files/directories in a directory |
45. Commonly Used Files Methods
| Method | Purpose |
|---|---|
Files.exists() | Checks whether a path exists |
Files.createFile() | Creates a file |
Files.createDirectory() | Creates a directory |
Files.createDirectories() | Creates directories and missing parents |
Files.readString() | Reads a text file into a string |
Files.readAllLines() | Reads lines from a text file |
Files.writeString() | Writes text to a file |
Files.copy() | Copies a file |
Files.move() | Moves or renames a file |
Files.delete() | Deletes a file or directory |
Files.deleteIfExists() | Deletes if the path exists |
Files.size() | Returns file size |
46. File Handling Workflow
A typical file-handling operation can follow these steps:
Create/Locate File
|
v
Check File
|
v
Open Resource
|
v
Read / Write Data
|
v
Handle Exceptions
|
v
Close ResourceWith try-with-resources, resource closing is handled automatically.
47. File Handling vs Database Storage
Files and databases serve different purposes.
| Files | Database |
|---|---|
| Simple data storage | Structured data storage |
| Useful for documents and logs | Useful for application records |
| Easy for small/simple data | Better suited to complex queries |
| Usually no built-in relational querying | Supports queries and relationships |
| Can be convenient for configuration and reports | Common for transactional applications |
For example, a configuration file may be appropriate for application settings, while customer records are often stored in a database.
48. Key Points to Remember
- File handling allows Java programs to work with files and directories.
- The traditional file API is available in
java.io. - Modern file-system operations are also provided through
java.nio.file. Filerepresents a file or directory path.Pathrepresents a file-system path in NIO.Filesprovides many useful operations for files and directories.FileReaderandFileWriterare commonly used for character data.FileInputStreamandFileOutputStreamwork with bytes.BufferedReaderis useful for reading text efficiently and line by line.Files.readString()andFiles.writeString()are convenient for text files.- File operations may throw
IOException. - Try-with-resources helps automatically close resources.
FileWriterwithout append mode can replace existing file contents.Files.copy()can create a file backup.Files.move()can move or rename a file.Files.delete()can remove a file or directory when permitted.- A
Fileobject by itself does not create a physical file. - Always consider whether the file contains text or binary data before selecting an appropriate API.
Conclusion
Java provides several APIs for handling files and directories. The traditional java.io package contains classes such as File, FileReader, FileWriter, BufferedReader, and FileInputStream.
The java.nio.file package provides the modern Path and Files APIs, which make many file-system operations straightforward.
For example:
Path path = Path.of("example.txt");
Files.writeString(path, "Hello Java!");
String content = Files.readString(path);
System.out.println(content);Understanding file creation, reading, writing, appending, copying, moving, and deleting is an important part of Java programming because many real-world applications need to work with information stored outside the application's memory.
See you in next page....🙂