Παράδειγμα: εγγραφή εικόνας

import java.io.*;

/**
 * Create a 256*256 24-bit color PNM RGB file containing all combinations
 * of R and G.
 * @author Diomidis Spinellis
 */
class ColorWrite {

    /** Write the specified ASCII string to out as bytes */
    static void writeStringAsBytes(OutputStream out, String s) throws IOException {
        for (int i = 0; i < s.length(); i++)
                out.write((byte)s.charAt(i));
    }

    public static void main(String args[]) {
	final String fileName = args[0];

	// Open file; try with resources
	try (var out =
                new BufferedOutputStream(new FileOutputStream(fileName))) {
            // NetPBM PPM 24-bit color file header
            // https://netpbm.sourceforge.net/doc/ppm.html
            writeStringAsBytes(out, "P6 256 256 255 ");
	    for (int r = 0; r < 256; r++)
		for (int g = 0; g < 256; g++) {
		    out.write(r);
		    out.write(g);
		    out.write(0);
		}
	} catch (FileNotFoundException e) {
	    System.err.println("Unable to open file " + fileName
		+ ": " + e.getMessage());
	    System.exit(1);
	} catch (IOException e) {
	    System.err.println("Error writing byte: " + e.getMessage());
	    System.exit(1);
	}
    }
}