4.2.1.3 - Text and binary files (Java)

4.2.1.3 - Text and binary files (Java)

Read and write structured text and binary data in Java, and use a stated file format to decide how values should be interpreted and tested.

Java route status: incomplete: runnable support pending. These are native written examples and code tasks.

Records and file formats

A file preserves data after a program stops, but its bytes need a shared interpretation before another program can use them.

A field is one item, such as a score; a record groups related fields, such as a candidate identifier and score. A text file encodes characters, so a line A17,82 can represent two fields separated by a comma. A binary file stores values in a defined non-text representation. Both kinds consist of bytes: the difference is how the program interprets them, not whether the file is stored electronically.

Specify separators, encoding, field order and expected types for text. For binary data, specify the type, size and order of every stored value. Writing Java integers and then trying to read them as doubles does not recover the same values. The filename extension alone does not define the format.

Text is convenient to inspect and exchange with simple tools, but parsing characters into numbers is necessary. Binary representations can avoid that conversion and use fixed-size numeric fields, but require a compatible reader. Neither format is inherently encrypted or guaranteed smaller for every dataset.

Text-file reading and writing

Text operations decode characters using an encoding and then interpret each line according to the file format.

The next methods belong inside a class with imports java.io.*, java.nio.file.* and java.nio.charset.StandardCharsets. scores.txt contains exactly one valid integer per nonblank line, with no blank lines. The file 12, 8, 15 on separate lines gives a total of 35.

Java
static int readTotal(Path source) throws IOException {
    int total = 0;
    try (BufferedReader reader = Files.newBufferedReader(
            source, StandardCharsets.UTF_8)) {
        String line;
        while ((line = reader.readLine()) != null) {
            total += Integer.parseInt(line.trim());
        }
    }
    return total;
}

static void writeScores(Path target, int[] scores) throws IOException {
    try (BufferedWriter writer = Files.newBufferedWriter(
            target, StandardCharsets.UTF_8)) {
        for (int score : scores) {
            writer.write(Integer.toString(score));
            writer.newLine();
        }
    }
}

readLine() returns a line without its line terminator, and returns null at end of file. An empty file therefore totals zero. trim() removes surrounding whitespace, not embedded punctuation. Integer.parseInt performs the text-to-number conversion. writer.write(score) would use the overload for a character code; Integer.toString(score) deliberately writes decimal digits.

Try-with-resources closes the reader or writer even if an exception occurs. In this default writing form, an existing target is replaced. Appending requires a deliberate StandardOpenOption.APPEND policy; it must not be assumed. These API operations and their options are defined in the Java Files documentation.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account