Learning Java/File IO

From Wikiversity
Jump to navigation Jump to search

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.


To use the objects presented in this section please add

import java.io.*;
import java.util.Scanner;

To the top of your .java file.


Files are another type of variable. You can make a file like this:

File f = new File("test.txt")

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[edit]

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


This class writes strings or char[] to a file. To create one:

FileWriter fw = new FileWriter("test.txt");//Create a filewriter writing to test.txt
FileWriter fw = new FileWriter("test.txt", true);//Do not delete contents of file - append to the end

It is as simple to write. After you create a FileWriter you can write strings to that file:

String s = "Testing";

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:

public void WriteHelloWorld(String Filename)
    FileWriter fw = new FileWriter(Filename);
    fw.write("My first written file!\n"); //\n signifies a new line
    fw.write("Hello World!\n");
  catch(IOException ex) //Did we generate an error?
    System.out.println("Could not write to file"); //Explain what happened
    System.exit(0); //Exit gracefully


File Input[edit]


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:

import java.util.Scanner;

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 ourScanner = new Scanner(new FileInputStream("ourfile.txt"));
Scanner ourScanner = new Scanner(new File("ourfile.txt"));
Scanner ourScanner = new Scanner("Even a String is a valid input");

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:

FileInputStream istream = new FileInputStream(Filename);
Scanner ourScanner = new Scanner(istream);
     Double tmp = ourScanner.nextDouble();

Using Strings and showing the use of extracting different data types

Scanner ourScanner = new Scanner("Rockefeller;John;43;180.5")

String lastName=ourScanner.next();
String firstName=ourScanner.next();
int age=ourScanner.nextInt();
double weight = ourScanner.nextDouble();


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[edit]

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

//Count the number of lines present in a file. 
//Inputs: Filename of chosen file
//Outputs: A count of the number of lines (int)
public int CountLines(String Filename)
  int count = 0;
    Scanner ourScanner = new Scanner(new File(Filename));
      ourScanner.next(); //Grab and forget the next line from the scanner
  catch(FileNotFoundException ex)
    System.out.println("File not Found");
  return count;

Comma Separated Value Files[edit]

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.