Learning Java/File IO

File input/output is quite similar to the System.in and System.out that you already have begun using In Java, files can be represented by the class java.io.File.

Imports
To use the objects presented in this section please add

To the top of your .java file.

Files
Files are another type of variable. You can make a file like this: This does not return an exception if the file doesn't exist. To check if it does: This will return a boolean.

To check if it is a file or directory: For a full list of methods you can use, go to File (Java 8 documentation).

File Output
To write to a file, you can use a FileWriter or a FileOutputStream.

FileWriter
This class writes strings or char[] to a file. To create one: It is as simple to write. After you create a FileWriter you can write strings to that file:

After you're done with your FileWriter you can save and close it using

Writing this simple code into Java will result in unhandled error exceptions. Because the FileWriter constructor may throw exceptions (such as the file being write-protected) we need to ensure that our code handles these in the event of an error. This code will not compile if the constructor is not placed within a try-catch block as below:

Scanner
Scanner is a class that was made when it was decided by Sun that the java file IO API was too messy. Scanners make file IO significantly easier. To use Scanner, import the class from java.util:

The scanner is a sort of wrapper class for a File, FileInputStream, or String class. The constructor of Scanner takes one of these objects as a parameter, like so:

Scanner includes a number of member methods that make reading Files easy. You can use a scanner to get the next item of a certain type from a stream with the methods next, nextDouble, nextFloat, nextInt, nextLine, etc.... You can also determine if more of a certain type exist with the has* methods and read and search for regular expressions.

Some example code:

Using Strings and showing the use of extracting different data types

Delimiters
Scanner splits the elements of the File/String on Whitespace (spaces, tabs, endlines) by default. You can set the delimiter of the scanner using

Where we have chosen the semi-colon ";" as a delimiter.

Handling Errors and an Example Function
As with writing to files Java forces us to handle exceptions that can be produced if our Scanner is fed by a File or FileInputStream object. Note that this try-catch structure is not necessary if your scanner is only operating on a String. Sample code which handles this is below

Comma Separated Value Files
Because CSV is such a popular format it deserves special attention. In this case we want to separate the lines by endline-characters ('\n') and the entries within each line by commas (','). A common strategy is to use two scanners, one which reads lines from the file and another for each line which reads the individual entries.