Java, Programming, Projects
Reading and Writing Files in Java
· Eric B.
![]()
File I/O in Java requires a handful of standard library classes, each with its own exception handling requirements. This tutorial covers two core operations: reading a text file line by line using Scanner, and writing a text file using both FileWriter and a BufferedWriter with UTF-8 encoding. Each approach includes a complete, runnable example.
If you need help with a Java assignment that involves file operations, see Java Assignment Help.
Reading a File Line by Line
Scanner reads a file line by line through its hasNextLine() and nextLine() methods. Point it at a File object, iterate, and close it in the finally block whether the read succeeds or not.
Start by declaring the file path. If the file sits in your project root, the filename alone works. For files elsewhere on disk, use the full path: on Windows c:\\folder\\subfolder\\file.txt, on Linux or Unix /var/www/subfolder/file.txt.
File file = new File("readme.txt");
The file below (readme.txt) has 10 lines:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
This program reads it and prints each line to the console:
import java.io.File;
import java.util.Scanner;
public class ReadingFile {
public static void main(String[] args) {
// File to read
File file = new File("readme.txt");
Scanner s = null;
try {
System.out.println("... reading file contents ...");
s = new Scanner(file);
// Read line by line
while (s.hasNextLine()) {
String line = s.nextLine(); // store the line
System.out.println(line); // print the line
}
} catch (Exception ex) {
System.out.println("Message: " + ex.getMessage());
} finally {
// Close the file whether reading succeeded or not
try {
if (s != null)
s.close();
} catch (Exception ex2) {
System.out.println("Message 2: " + ex2.getMessage());
}
}
}
}
The Scanner object advances one line per iteration. The finally block closes the file even when an exception fires mid-read. This keeps the file handle from leaking when the process runs in a long-lived server or is called repeatedly.
For modern Java (7+), consider try-with-resources to handle closing automatically. The pattern above works in any Java version.
Writing a File
Java gives you two straightforward paths for writing a text file: FileWriter for simple output and BufferedWriter + OutputStreamWriter when you need a specific character encoding such as UTF-8. Both write line by line from an array.
The array used in both examples:
String[] lines = { "one", "two", "three", "four", "five", "six", "seven", "..." };
Writing Without a Specific Encoding
FileWriter accepts a filename (or a File object). If the file does not exist, Java creates it. Pass the full path if you want the file saved somewhere other than the project folder.
Write to the file incrementally, one element at a time. Buffering the entire string in memory before writing risks an OutOfMemoryError on large files.
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String[] args) {
String[] lines = { "one", "two", "three", "four", "five", "six", "seven", "..." };
FileWriter file = null;
try {
file = new FileWriter("writtenfile.txt");
// Write line by line
for (String line : lines) {
file.write(line + "\n");
}
file.close();
} catch (Exception ex) {
System.out.println("Exception message: " + ex.getMessage());
}
}
}
Running this produces writtenfile.txt with the following contents:
one
two
three
four
five
six
seven
...
Writing With UTF-8 Encoding
When the output file must use a specific encoding, chain OutputStreamWriter around a FileOutputStream and specify the charset name. Wrapping that in a BufferedWriter buffers the output for efficiency.
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
public class FileWriterUtf8 {
public static void main(String[] args) {
String[] lines = { "one", "two", "three", "four", "five", "six", "seven", "..." };
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("writtenfile2.txt"), "UTF-8"));
// Write line by line
for (String line : lines) {
try {
out.write(line + "\n");
} catch (IOException ex) {
System.out.println("Writing exception: " + ex.getMessage());
}
}
} catch (UnsupportedEncodingException | FileNotFoundException ex2) {
System.out.println("Error message 2: " + ex2.getMessage());
} finally {
try {
out.close();
} catch (IOException ex3) {
System.out.println("Error closing file: " + ex3.getMessage());
}
}
}
}
This produces writtenfile2.txt with the same content as the first example, encoded in UTF-8. The finally block closes the writer even when an exception fires during the loop.
Related Reading
- Java Assignment Help -- expert Java developers available for assignments at any level
- Java File I/O: Read, Write, and Manage Files -- deeper coverage of NIO,
Path,Files, and serialization - Exception Handling in Java: Full Guide -- checked vs unchecked exceptions, try-with-resources, and custom exception design
Related articles
- Java
Advanced Java Data Management Techniques
Master advanced Java data management: optimize data structures, handle concurrent access, tune memory, and use serialization and compression in real applications.
May 3, 2024
- Java
Java File I/O: Read, Write, and Manage Files
A practical guide to Java file I/O: streams, readers and writers, NIO Path and Files, buffering, serialization, and the exceptions that break file code.
Oct 7, 2023
- Java
Exception Handling in Java: Full Guide
How exception handling in Java works: checked vs unchecked, try-catch-finally, throw and throws, custom exceptions, try-with-resources, and the mistakes to avoid.
Sep 25, 2023


