-
Notifications
You must be signed in to change notification settings - Fork 1
File IO
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.
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.
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.
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 to files is similar to reading a file. However there are several differences. To start with, instead of using the scanner object, we use another object called the FileWriter which we will use to write to a file. Second, we don't need a while loop to read through the file, we can just use the write method from FileWriter to write what we want. However, careful! Using the write method by itself will overwrite contents of the file. If you want to add (or append) to a file, we need to specify when creating the FileWriter object that you want to append to a file.
import java.io.File;
import java.io.FileWriter;
public class WriteFile {
public static void main(String[] args) {
try {
File file = new File ("file.txt");
//This will overwrite the contents of a file
FileWriter fileWriter = new FileWriter(file);
//This will append to a file
FileWriter fileWriter2 = new FileWriter(file, true);
fileWriter.write("hello!");
fileWriter2.write("hello2!");
//Like the scanner, the FileWriter object should also be closed to avoid future mishap
fileWriter.close();
fileWriter2.close();
} catch (Exception e) {
System.out.println ("File not found");
}
}
}
hello!hello2!
Note that a new line will NOT be automatically inserted, you must specify a new line by using the "\n" at the end of the string!
For example,
fileWriter.write("hello!\n");
fileWriter2.write("hello2!");
hello!
hello2!