Lesson 6: File IO
Introduction
It’s time to play with some files. In this lessons, we will learn how to read and write to text files. Basically, instead of having you to copy and paste the content of text whatever you want to play with into the program, you can just use one of the classes to do that for you.
Basically, the class reads the file for you, and stores the content of the file, which you can use.
Lets have an example below.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Here are the classes we will be using.
- Java.io.BufferedReader: create buffer(temporary memory) for reader classes.
- Java.io.FileReader: class that will actually “read” the file.
- Java.io.IOException: we will deal with this later.
public class BufferedReaderExample {
public static void main(String[] arg) {
BufferedReader br = null;
First, we declare the class. Let’s call it “BufferedReaderExample”. In the main, we will first declare our bufferedreader, br(“B”uffered “R”eader) and equate it to null, for the reasons we will discuss later.
String sCurrentLine;
br = new BufferedReader(new FileReader("C://testing.txt"));
while((sCurrentLine = br.readLine()) != null){
System.out.println(sCurrentLine);
}
String sCurrentLine – declares a string variable called sCurrentLine.
br – remember the BufferedReader variable we created above? Now we will have output of FileReader stored in it.
While -> readLine method moves to the next line, and condition of (!=null) checks whether there is any more lines or not.
--
However, here we face an important problem. It’s exceptions (or errors). Lets say, we want to use “testing file.txt” in C, as in the example. However, what if, there is no such file as “testing.txt” in C? We will get an error, and we need to handle the error somehow.
Remember IOException, one of the first three we imported in the beginning? The “error-handling” class will be used in this case.
So, we first wrap our code using “try {}” phrase.
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
String sCurrentLine;
while((sCurrentLine = br.readLine()) != null){
System.out.println(sCurrentLine);
}
}
then, if we “failed” to try, we catch whatever error there is. In this case, as we have Input-Output-Exception error, we are using “IOException”
catch (IOException e) {
e.printStackTrace
}
printStackTrace is similar to console.log of errors. We are not going to do anything but to print what happened, so the user knows.
Thus, the entire code will look like this, with extra brackets in the end.
package your.package.name;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Since we have learned how to read files, lets learn how to write to files.
Instead of
import java.io.BufferedReader; <br>
import java.io.FileReader;
We have
import java.io.File;<br>
import java.io.FileOutputStream;
This time. As the name suggests, they got to do with writing files. Let's begin with creating the class called WrtieFileExample.
public class WriteFileExample {
public static void main(String[] args) {
Then, since we're writing to file, it exists or not does not matter.
File file = new File("c:/newfile.txt");
String content = "This is the text content";
What we're doing is pretty obvious in the syntax. We will use our try-catch we learend previously, to prevent any malicious things happening.
try (FileOutputStream ops = new FileOutputStream(file)) {
if (!file.exists()) {
// if file doesn't exist, then we create it
file.createNewFile();
}
Here, we created File Output Stream, just liked we created Buffered Reader(they are the similar syntax) and we will create the file if it does not exist. This part is very human-readable, I agree.
// get the content in bytes
byte[] contentInBytes = content.getBytes();
ops.write(contentInBytes);
ops.flush();
ops.close();
System.out.println("Done");
}
We close the loop, at the same time we wrtie the contents. We first convert our string into bytes, and we write the content to the file. Then, we "flush" our stream, as we clear(empty) the stream we have used. Finally, we close the stream, implying no more outputs to the file.
As usual, if there's an error, we catch it!
catch (IOException e) {
e.printStackTrace();
}
This is how it looks in the end :
package your.package.name;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
File file = new File("c:/newfile.txt");
String content = "This is the text content";
try (FileOutputStream ops = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
ops.write(contentInBytes);
ops.flush();
ops.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}