Reading and Writing Files in Java, with Examples
In this tutorial we'll see how to read and write files in Java, one of the most useful and commonly used tasks when programming. Learn it with examples.
You can download the project for this post by clicking HERE.
In this tutorial we are going to see how to read and write files in Java, since it is one of the most useful and commonly used things when programming. It’s true that the code you have to write to read and write files is quite tedious and long, because you have to use objects of classes that aren’t used very often and you have to define several exceptions (see the tutorial "Exceptions (Exception) in Java, with examples") depending on how you read and write the files.
Although reading and writing files can be done in several ways, in this tutorial we are going to give you the code needed to perform these actions, even though it can also be done in other ways:
Reading Files:
First, we are going to read the contents of the following file (called 'fichero_leer.txt') and print what we read to the screen:
Linea 1
Linea 2
Linea 3
Linea 4
Linea 5
Linea 6
Linea 7
Linea 8
Linea 9
Linea 10
First we have to specify the path or directory where the file we want to read is located. If the file is in our project folder (as is the case in the project we are building), we only need to write the file name; otherwise, we have to specify the path where the file is located (e.g. -> Windows: c:\\carpeta\……\fichero.txt, Linux or Unix: \var\www\……\fichero.txt). We do it like this:
File fichero = new File("fichero_leer.txt");
Once we have the file we want to read, we create an object of the "Scanner" class and read the file line by line. Below is the program that reads the file line by line and prints the contents of the file to the screen, line by line:
import java.io.File;
import java.util.Scanner;
public class LecturaFicheros {
public static void main(String[] args) {
// File we want to read from
File fichero = new File("fichero_leer.txt");
Scanner s = null;
try {
// Read the contents of the file
System.out.println("... Leemos el contenido del fichero ...");
s = new Scanner(fichero);
// Read the file line by line
while (s.hasNextLine()) {
String linea = s.nextLine(); // Store the line in a String
System.out.println(linea); // Print the line
}
} catch (Exception ex) {
System.out.println("Mensaje: " + ex.getMessage());
} finally {
// Close the file whether the reading succeeded or not
try {
if (s != null)
s.close();
} catch (Exception ex2) {
System.out.println("Mensaje 2: " + ex2.getMessage());
}
}
}
}
In the code we can see that our 's' object of the "Scanner" class moves through the file line by line, and in the "while" loop we ask it for the next line, if there is one.
We also see in the code that we have to handle several exceptions, so that if one of them occurs, the program doesn’t stop running. For example, at the end of the code (in the "finally") we can see how the file gets closed regardless of whether there was an error while reading it.
In short, here we have given you the code so you can read a text file (in this case a 'txt') line by line.
Writing Files:
For writing files, we are going to present two ways of doing it: one to write a file without a specific encoding and another to write it with a specific encoding (in this case UTF-8).
In these examples we are going to write each element of the following array to the file (line by line):
String[] lineas = { "Uno", "Dos", "Tres", "Cuatro", "Cinco", "Seis", "Siete", "..." };
The simplest way to do this writing (using a foreach over the array) is the one we present below:
import java.io.FileWriter;
public class EscrituraFicheros {
public static void main(String[] args) {
String[] lineas = { "Uno", "Dos", "Tres", "Cuatro", "Cinco", "Seis", "Siete", "..." };
/** WRITING METHOD 1 **/
FileWriter fichero = null;
try {
fichero = new FileWriter("fichero_escritura.txt");
// Write to the file line by line
for (String linea : lineas) {
fichero.write(linea + "\n");
}
fichero.close();
} catch (Exception ex) {
System.out.println("Mensaje de la excepción: " + ex.getMessage());
}
}
}
As we can see in this program, we only use an object of the "FileWriter" class, to which we pass the file name. If the file doesn’t exist, it creates it. Really, you don’t just have to pass the file name, but the path where we want to save the file plus the file name, although if we do it as in the program, it will save the file in the project folder.
Another very important thing is that we open the file and write to it little by little (element by element of the array), and at the end, once we have written everything, we close the file (the "close()" method). Really, when writing to a file, what we do is pass it some content (in this case a String) and it writes it to the file. We recommend that you write little by little, because if you store the content to write in a String variable and then write it all at once, you may get an out-of-memory exception if what you have to write to the file is very large; so do it as shown here and you won’t have that problem.
As a result of running this program, you will have a new file called "fichero_escritura.txt" with the following content:
Uno
Dos
Tres
Cuatro
Cinco
Seis
Siete
...
The second way, writing a file with a specific encoding, is the one we present below:
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 EscrituraFicheros {
public static void main(String[] args) {
String[] lineas = { "Uno", "Dos", "Tres", "Cuatro", "Cinco", "Seis", "Siete", "..." };
/** WRITING METHOD 2. With the file encoded in UTF-8 **/
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("fichero_escritura2.txt"), "UTF-8"));
// Write to the file line by line
for (String linea : lineas) {
try {
out.write(linea+"\n");
} catch (IOException ex) {
System.out.println("Mensaje excepcion escritura: " + ex.getMessage());
}
}
} catch (UnsupportedEncodingException | FileNotFoundException ex2) {
System.out.println("Mensaje error 2: " + ex2.getMessage());
} finally {
try {
out.close();
} catch (IOException ex3) {
System.out.println("Mensaje error cierre fichero: " + ex3.getMessage());
}
}
}
}
This way is a bit more complex and you have to handle several exceptions, but it lets us write to the file in the format we specify.
The result is the same content as in the previous file, but in this case with the name "fichero_escritura2.txt".
“Reading and Writing Files in Java, with Examples” by Ricardo Moya at jarroba.com, licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Registered at Safe Creative.

You may also like
Reading and Writing Files in Python, with Examples
In this tutorial you'll learn how to read and write files in Python, one of the most useful and commonly used tasks when programming. Examples included.
ArrayList in Java, with Examples
Learn how to use ArrayList in Java: add, remove and iterate elements, store objects, and work with nested ArrayLists, with practical examples.


Leave a comment