Shiklo Programming
EN
  • English
  • Español
  • Português
  • Deutsch
  • Français
  • 日本語
  • हिन्दी

Java Files (Create and Write)

Variables disappear when a program ends. To keep data, such as scores, notes or settings, a program writes it to a file. Modern Java does this with the Files class and the Path type from java.nio.file. In our editor the files are created in your project, so you can open them in the file list after running a program.

Writing a file

Path.of("notes.txt") names a file in the current folder. Files.writeString creates the file (or replaces it) with the given text. Methods of Files can throw an IOException, a checked exception, so main declares throws IOException (see Throw and Throws):

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("notes.txt");
        Files.writeString(file, "Buy milk\nCall Ravi\n");
        System.out.println("Exists: " + Files.exists(file));
        System.out.println("Size: " + Files.size(file) + " bytes");
        System.out.print(Files.readString(file));
    }
}
Output
Exists: true
Size: 19 bytes
Buy milk
Call Ravi

Files.readString reads the whole file back as one string; the next topic, Read Files, covers reading in detail.

Appending and writing lines

To add to the end of a file instead of replacing it, pass the option StandardOpenOption.APPEND. Files.write with a list writes each item as one line:

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 log = Path.of("log.txt");
        Files.write(log, List.of("Started", "Loaded 3 users"));
        Files.writeString(log, "Finished\n", StandardOpenOption.APPEND);
        List<String> lines = Files.readAllLines(log);
        System.out.println(lines.size() + " lines:");
        for (String line : lines) {
            System.out.println("- " + line);
        }
    }
}
Output
3 lines:
- Started
- Loaded 3 users
- Finished

Writing with a BufferedWriter

When a program writes many lines one at a time, a BufferedWriter is efficient. Open it in a try-with-resources block so it is closed (and its content saved) automatically:

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Path table = Path.of("table.txt");
        try (BufferedWriter out = Files.newBufferedWriter(table)) {
            for (int i = 1; i <= 5; i++) {
                out.write("5 x " + i + " = " + (5 * i));
                out.newLine();
            }
        }
        System.out.println(Files.readAllLines(table).get(4));
    }
}
Output
5 x 5 = 25

Folders, copying, renaming and deleting

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class Main {
    public static void main(String[] args) throws IOException {
        Path dir = Path.of("backup");
        Files.createDirectories(dir);
        Path original = Path.of("data.txt");
        Files.writeString(original, "important");
        Path copy = dir.resolve("data-copy.txt");
        Files.copy(original, copy, StandardCopyOption.REPLACE_EXISTING);
        Path renamed = dir.resolve("data-old.txt");
        Files.move(copy, renamed, StandardCopyOption.REPLACE_EXISTING);
        System.out.println(Files.exists(copy) + " " + Files.exists(renamed));
        System.out.println(renamed.getFileName());
        Files.delete(original);
        System.out.println(Files.exists(original));
        System.out.println(Files.isDirectory(dir));
    }
}
Output
false true
data-old.txt
false
true

resolve builds a path inside a folder. Files.delete throws an exception if the file does not exist; Files.deleteIfExists does not.

Practice exercises

  1. Ask the user for three items and write them to shopping.txt, one per line.
  2. Every time the program runs, append the current date to visits.txt and print how many lines the file has.
  3. Create a folder reports and write summary.txt inside it.