File handling in Java allows programs to create, read, write, append, and manage files. Java provides classes such as File, FileReader, FileWriter, BufferedReader, and the modern Files utility.
File handling means working with files stored on a computer. A Java program can use file handling to save information permanently instead of keeping it only in memory.
Common file operations include:
The java.io.File class represents a
file or directory path. It provides methods to
check existence, inspect names, and perform
certain file-system operations.
import java.io.File;
class Main {
public static void main(String[] args) {
File file = new File("data.txt");
System.out.println(file.getName());
System.out.println(file.exists());
}
}
data.txt
false
The second line is false if data.txt does not exist at the path resolved from the program's working directory.
The createNewFile() method creates
a new empty file if the file does not already exist.
import java.io.File;
import java.io.IOException;
class Main {
public static void main(String[] args) {
try {
File file = new File("data.txt");
if (file.createNewFile()) {
System.out.println("File created");
} else {
System.out.println("File already exists");
}
} catch (IOException e) {
System.out.println("File creation failed");
}
}
}
File created
The output depends on whether the file already exists and whether the program has permission to create it.
The FileWriter class writes characters
to a text file. By default, this constructor
overwrites existing content.
import java.io.FileWriter;
import java.io.IOException;
class Main {
public static void main(String[] args) {
try (FileWriter writer =
new FileWriter("data.txt")) {
writer.write("Welcome to Java File Handling");
System.out.println("Data written successfully");
} catch (IOException e) {
System.out.println("Writing failed");
}
}
}
Data written successfully
After running the program, data.txt contains the text written by the program.
Scanner can read text from a file. The following example reads the file one line at a time.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
try (Scanner sc =
new Scanner(new File("data.txt"))) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
}
Welcome to Java File Handling
This program prints each line until the file has no more lines to read.
FileReader reads character data from a text file. You can read one character at a time.
import java.io.FileReader;
import java.io.IOException;
class Main {
public static void main(String[] args) {
try (FileReader reader =
new FileReader("data.txt")) {
int ch;
while ((ch = reader.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException e) {
System.out.println("Reading failed");
}
}
}
The read() method returns -1 when the end of the file is reached.
To append text without replacing existing content, create FileWriter with the append argument set to true.
import java.io.FileWriter;
import java.io.IOException;
class Main {
public static void main(String[] args) {
try (FileWriter writer =
new FileWriter("data.txt", true)) {
writer.write(System.lineSeparator());
writer.write("This is a new line.");
System.out.println("Data appended successfully");
} catch (IOException e) {
System.out.println("Appending failed");
}
}
}
Data appended successfully
The new text is added to the end of the file instead of replacing its previous contents.
BufferedReader reads text efficiently by buffering characters and provides a convenient readLine() method.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class Main {
public static void main(String[] args) {
try (BufferedReader reader =
new BufferedReader(
new FileReader("data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Unable to read file");
}
}
}
The loop continues until readLine() returns null, which means there are no more lines.
The File class provides methods for checking basic information about a path.
import java.io.File;
class Main {
public static void main(String[] args) {
File file = new File("data.txt");
System.out.println("Name: " + file.getName());
System.out.println("Exists: " + file.exists());
System.out.println("Readable: " + file.canRead());
System.out.println("Writable: " + file.canWrite());
System.out.println("Size: " + file.length());
}
}
The results depend on the actual file and the operating system's permissions.
Note: length() returns the file size in bytes for an ordinary file. Its value is not a character count for text files.
The delete() method attempts to
delete a file or an empty directory.
import java.io.File;
class Main {
public static void main(String[] args) {
File file = new File("data.txt");
if (file.delete()) {
System.out.println("File deleted");
} else {
System.out.println(
"File could not be deleted"
);
}
}
}
The delete() method returns true if the deletion succeeds and false otherwise.
The java.nio.file package provides
modern utilities for working with paths and files.
Files.writeString() and Files.readString() are
available in Java 11 and later.
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
class Main {
public static void main(String[] args) {
Path path = Path.of("data.txt");
try {
Files.writeString(
path,
"Hello from Java NIO"
);
String content = Files.readString(path);
System.out.println(content);
} catch (IOException e) {
System.out.println("File operation failed");
}
}
}
Hello from Java NIO
Files.writeString() creates the file if necessary and replaces its existing content by default. Files.readString() reads the file as a string.
1. Which class can create a new empty file?
2. How do you append text using FileWriter?
3. Which method reads a complete text file into a String in Java 11 and later?