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.

Some examples here

Writing files

Some more examples

Activity

Clone this wiki locally