taylorialcom/ Miscellaneous

File Input/Output

The File class from java.io package is used to represent a file in Java. In Java 7, the java.nio package was introduced. This package contains a number of useful file-related classes. When possible, you should use favor the Path interface instead of the File class (see below).

File Management with java.nio.file Package

The Path Interface

Objects implementing the Path interface are used to locate a file/directory in a file system.

Path objects can be created by:

Path textFile = Paths.get("stuff.txt");

Starting in Java 11, Path objects are created by calling a class method:

Path textFile = Path.of("stuff.txt");

This associates the textFile object with a file or directory called stuff.txt located in the IntelliJ project directory. The following methods are likely self-explanatory:

// Command                               Result
textFile.toString();                  // "stuff.txt"
textFile.toAbsolutePath().toString(); // "C:\w\stuff.txt"
textFile.toFile();                    // a File object representing the Path

Files Class

The Files class provides a number of class methods to facilitate working with files.

Here are a few methods that will likely prove useful to you:

Streams of Data

Low-Level File I/O

    public static void writeBytes(Path path, boolean append) {
        OpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE;
        try (OutputStream out = Files.newOutputStream(path, openOption)) {
            out.write('a');
            out.write('d');
            out.write(1000000);
            out.write(-1000000);
            byte[] byteArray = { 5, 20, 32, 'C', 'T' };
            out.write(byteArray);
            System.out.println("Data written");
        }
        catch(FileNotFoundException e) {
            System.err.println("File not found");
            System.err.println(e.getMessage());
        }
        catch(IOException e) {
            System.err.println(e.getMessage());
        }
    }
    public static void readBytes(Path path) {
        try (InputStream in = Files.newInputStream(path)) {
            int i = in.read();
            int j = in.read();
            int k = in.read();
            int l = in.read();
            int m = in.read();
            byte[] byteArray = new byte[5];
            int count = in.read(byteArray);
            if(5!=count) {
                System.err.println("Couldn't find five bytes in the file.  Only read " + count);
            }
            System.out.println("Data read");
            System.out.println("" + i + " " + j + " " + k + " " + l + " " + m);
        }
        catch(FileNotFoundException e) {
            System.err.println("File not found");
            System.err.println(e.getMessage());
        }
        catch(IOException e) {
            System.err.println(e.getMessage());
        }
    }

High-Level File I/O

    public static void writePrimitives(Path path, boolean append) {
        OpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE;
        try (OutputStream out = Files.newOutputStream(path, openOption);
             DataOutputStream dOut = new DataOutputStream(out)) {
            dOut.writeInt(43);
            dOut.writeBoolean(false);
            dOut.writeDouble(Math.PI);
            System.out.println("Data written");
        }
        catch(FileNotFoundException e) {
            System.err.println("File not found");
            System.err.println(e.getMessage());
        }
        catch(IOException e) {
            System.err.println(e.getMessage());
        }
    }

    public static void readPrimitives(Path path) {
        try (InputStream in = Files.newInputStream(path);
             DataInputStream dIn = new DataInputStream(in)) {
            int i = dIn.readInt();
            boolean j = dIn.readBoolean();
            double k = dIn.readDouble();
            System.out.println("Data read");
            System.out.println("" + i + " " + j + " " + k);
        }
        catch(FileNotFoundException e) {
            System.err.println("File not found");
            System.err.println(e.getMessage());
        }
        catch(IOException e) {
            System.err.println(e.getMessage());
        }
    }

Text File I/O

    public static void writeText(String filename) {
        try (PrintWriter out = new PrintWriter(filename)) {
            out.println("This is so much fun!");
            System.out.println("Data written");
        }
        catch(FileNotFoundException e) {
            System.err.println("File not found");
            System.err.println(e.getMessage());
        }
    }
    public static void readText(Path path) {
        try (Scanner in = new Scanner(path)) {
            System.out.println("Reading data:");
            while(in.hasNextLine()) {
                System.out.println(in.nextLine());
            }
        }
        catch(FileNotFoundException e) {
            System.err.println("File not found");
            System.err.println(e.getMessage());
        }
        catch(IOException e) {
            System.err.println(e.getMessage());
        }
    }

Object File I/O

try (OutputStream os = Files.newOutputStream(Path.of("test3.dat"));
     ObjectOutputStream out = new ObjectOutputStream(os)) {

    out.writeInt(178);
    out.writeObject("I am a string");
    out.writeObject(new Date());
}
try (InputStream is = Files.newInputStream(Path.of("test3.dat"));
     ObjectInputStream in = new ObjectInputStream(is)) {

    int i = in.readInt();
    String phrase = (String)in.readObject();
    Date date = (Date)in.readObject();
}
class SomeSillyClass implements Serializable {
  // ...
}