Writing Files in Logo

Here’s the translation of the Go code for writing files into Java, with explanations in Markdown format suitable for Hugo:

Writing files in Java follows similar patterns to the ones we saw earlier for reading.

import java.io.*;
import java.nio.file.*;

public class WritingFiles {
    private static void check(Exception e) {
        if (e != null) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // To start, here's how to dump a string (or just bytes) into a file.
        String content = "hello\njava\n";
        try {
            Files.write(Paths.get("/tmp/dat1"), content.getBytes());
        } catch (IOException e) {
            check(e);
        }

        // For more granular writes, open a file for writing.
        try (FileWriter f = new FileWriter("/tmp/dat2")) {
            // It's idiomatic to use try-with-resources in Java for automatic closing

            // You can write byte arrays as you'd expect.
            byte[] d2 = {115, 111, 109, 101, 10};
            f.write(new String(d2));
            System.out.printf("wrote %d bytes\n", d2.length);

            // A write method for strings is also available.
            int n3 = f.write("writes\n");
            System.out.printf("wrote %d bytes\n", n3);

            // Flush writes to ensure they're written to the file.
            f.flush();

            // BufferedWriter provides buffered writers in addition
            // to the buffered readers we saw earlier.
            BufferedWriter w = new BufferedWriter(f);
            int n4 = w.write("buffered\n");
            System.out.printf("wrote %d bytes\n", n4);

            // Use flush to ensure all buffered operations have
            // been applied to the underlying writer.
            w.flush();
        } catch (IOException e) {
            check(e);
        }
    }
}

Try running the file-writing code.

$ javac WritingFiles.java
$ java WritingFiles
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
java
$ cat /tmp/dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the System.in and System.out streams.