[!NOTE] Until now, all of our application data existed exclusively in RAM. If we restarted the program, all variables vanished. To permanently persist data (without diving into complex SQL databases), we write it to hard disk files.
The java.io.File class allows us to create and read files from the host Operating System.
Creating and Writing to a File
When writing a file, we utilize the FileWriter class. Remember our lesson on the try-catch block? File operations touch external hardware, meaning they are highly prone to crashing (e.g., hard drive is full, lacking admin permission). Therefore, Java enforces a try-catch block for all I/O operations via Checked Exceptions.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteExample {
public static void main(String[] args) {
// Explicitly required try/catch!
try {
// 1. Target the file (it will create it if it doesn't exist!)
FileWriter myWriter = new FileWriter("filename.txt");
// 2. Write the string payload
myWriter.write("Java File I/O is easier than you think. Logging data to disk...");
// 3. MANDATORY: Close the stream! If you forget this, the data may never actually flush to the disk!
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred. Check permission restrictions.");
e.printStackTrace();
}
}
}
Reading from a File
To read from a file, we can hook our good friend the Scanner up to a File Object, rather than hooking it up to System.in (the keyboard).
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadExample {
public static void main(String[] args) {
// Required to catch specific non-existent files
try {
// 1. Establish the target
File myObj = new File("filename.txt");
// 2. Inform the Scanner to read the File, not the Keyboard!
Scanner myReader = new Scanner(myObj);
// 3. Loop through every line until the end of the file is reached
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
// 4. Free up memory!
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("The requested file was completely missing!");
}
}
}
[!TIP] Getting File Meta Info: Before reading, you can execute
myObj.exists()to check if it's there safely. You can also runmyObj.length()to get the exact file size in bytes to prevent attempting to load a 100GB text file into a 2GB RAM container!