Careeroza
Reading and Writing Files
Write, Append and Read
Example
The example uses a temporary file and deletes it at the end, so it is safe to run anywhere.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("notes", ".txt");
try {
Files.writeString(file, "Line 1: Learn Java" + System.lineSeparator());
Files.writeString(file, "Line 2: Practice daily" + System.lineSeparator(), StandardOpenOption.APPEND);
Files.write(file, List.of("Line 3: Build projects", "Line 4: Get hired"), StandardOpenOption.APPEND);
System.out.println("Exists: " + Files.exists(file));
System.out.println("--- readString ---");
System.out.print(Files.readString(file));
List<String> lines = Files.readAllLines(file);
System.out.println("--- readAllLines: " + lines.size() + " lines ---");
System.out.println("Last line: " + lines.get(lines.size() - 1));
} finally {
Files.deleteIfExists(file);
System.out.println("Deleted: " + !Files.exists(file));
}
}
}Output
Exists: true --- readString --- Line 1: Learn Java Line 2: Practice daily Line 3: Build projects Line 4: Get hired --- readAllLines: 4 lines --- Last line: Line 4: Get hired Deleted: true
Handling Missing Files
Example
Reading a file that does not exist throws NoSuchFileException (a subclass of IOException).
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) {
Path config = Path.of("does-not-exist", "app.properties");
try {
String text = Files.readString(config);
System.out.println(text);
} catch (NoSuchFileException e) {
System.out.println("Config not found, using defaults");
} catch (IOException e) {
System.out.println("Could not read config: " + e.getMessage());
}
}
}Output
Config not found, using defaults
Character Encoding
Files.readString and Files.writeString use UTF-8 by default, which handles Hindi, Tamil and emoji correctly. Old FileReader/FileWriter code used the platform default, which caused garbled text on Windows. If you must, pass the charset explicitly: Files.readString(path, StandardCharsets.UTF_8).