Skip to content

File IO

Byung Hun Lee edited this page Jan 17, 2018 · 6 revisions

Overview

So far, we have seen how we can write programs to accept user input through the console line during the program's execution. Programs can also communicate through stored data, such as files. We will be going over how to integrate storing/writing data to files.

New Concepts

I/O Streams

A stream is a communication channel that a program has with the outside world. It is used to transfer data ; in our case, we will be utilizing I/O Streams, which represents an input source or an output destination.

No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data.

Reading files

To read from a file (ie. a text file) the program first require a scanner object like the one used before to input text while a code was running. However, instead of creating a Scanner object that will be taking system inputs, the scanner inputs will be taking files.

For example, say we have a file called file.txt

//The first step is to import two necessary java library, java.util.Scanner, and java.io.File
//The two libraries contain the needed methods to read from a file.
import java.util.Scanner;
import java.io.File;

public class ReadFile{

   public static void main (String[] args){

      //Second, reate a file object, which will contain the name of the file you want to read
      File file = new File("file.txt");
      //Lastly, create a scanner object that will scan the file object
      Scanner fileReader = new Scanner(file);
   }
}

Unfortunately, the above code will throw an error. Why? Because Java doesn't like the possibility of a file not existing. So, to please our code we require the try/catch statement.

What is the try/catch statement?

The definition is in the name. The code tries to do something, and if there's an error in the program ie. a certain file cannot be found, the code will catch that error.

Using the above example,

try{
   File file = new File("file.txt");
   Scanner fileReader = new Scanner(file);
} catch (Exception e){
   System.out.println("File not found!");
}

With this the code will print "File not found!" in the event file.txt cannot be found. The argument following the catch statement is used to specify what type of error the catch statement should look for. The specific error we should be looking for is: FileNotFoundException, however using that exception requires importing another library so instead we use the Exception error to say use this code for every error found in the try statement.

Okay, so we now have a scanner that can read file.txt, but how do we actually read the contents of the file? We can use a while loop to read the file until the end.

For example,

try{
   File file = new File("file.txt");
   Scanner fileReader = new Scanner(file);

   //Using the hasNext function, we can continue running through the loop as long as there's input left
   while (fileReader.hasNext()){
      String a = fileReader.next();
      System.out.println(a);
   }

   //It is recommended you close the scanner to prevent unwanted problems from arising later
   fileReader.close();

} catch (Exception e){
   System.out.println("File not found!");
}

###Full Example of Reading File If our file that we want to read contains the text: test1 test2 test3

import java.io.File;
import java.util.Scanner;

public class ReadFile {

	public static void main(String[] args) {
		
		try {
			File file = new File ("file.txt");
			Scanner fileReader = new Scanner(file);
			
			while (fileReader.hasNext()) {
				String a = fileReader.next();
				System.out.println(a);
			}
			
			fileReader.close();
			
		} catch (Exception e) {
			System.out.println ("File not found");
		}
	}
}

test1
test2
test3

Writing files

Some more examples

Activity

Clone this wiki locally