Java I/O

Input and Output in Java is pretty powerful. Java can read streams, sockets, files etc using many java standard libraries java.io.* . There are many practical uses for this including those resume files that you have uploaded on the job portal web pages . Now you know the use 🙂

Let’s create a simple file with the a simple text content in the same folder as the sources.

Now, let’s create a small java program to read the content of the file and print it out on the console.The first change would be that the Class

[java title=”CharacterStream.java” gutter=”true” highlight=”10″]
//Import the I/O java library
import java.io.*;
/*
* The purpose of this program is to illustrate
* how to read and write character streams
* A sample text file read_text.txt will be used with the
* text "Hello World n This is Siva"
* We will read the file and write the file
* to another text file write_text.txt
*/

public class CharacterStream {

public static void main(String[] args) {
// We will use the FileReader object in the java.io
// library to read the file

StringBuffer sb;

try {
FileReader fr = new FileReader ("read_text.txt");

int read ;

while ( (read=fr.read()) != -1)
{
System.out.println (read);
}

}catch (IOException e)
{
System.out.println ( "Could not read file -> " +e );
}

}
}
[/java]

Output : Here is the output

[java title=”CharacterStream.java” gutter=”true” highlight=”10″]
Error during file read -> java.io.FileNotFoundException: read_text.txt (The system cannot find the file specified)
The contents of the file are
[/java]

Not quite the input we expected right ? The reason is that we did not give the absolute file path. Now, if we give just the file name, Java is looking for the file in the path where we started Java. In this case this is the file path of where Eclipse got started.

Now, lets try this again.

[java title=”CharacterStream.java” gutter=”true” highlight=”10″]
73
32
104
97
118
101


[/java]

Again, not what we are expecting right ? What is happening here ?  Remember our text ? “I have some text in the file read_text.txt” . The ASCII value of the letter “I” is 73 and the ASCII value of the letter  blank is 32 and so on.. Doesn’t help much right ?Let us see if we can reconstruct the file, by writing it back and try to open the same file in the editor.

We will use a new FileWriter class and write the character that we have read and write a file write_text.txt

[java title=”CharacterStream.java” gutter=”true” highlight=”3,9″]
try {
FileReader fr = new FileReader ("read_text.txt");
FileWriter fw = new FileWriter ("write_text.txt");

int read ;

while ( (read=fr.read()) != -1)
{
fw.write(read);
}

[/java]

Still we don’t see anything in the file. Why is that ? The FileWriter Object needs to be explicitly closed before it writes anything to the stream.So, let’s close the FileWriter stream by calling the close method.

[java title=”CharacterStream.java” gutter=”true” highlight=”10″]
try {
FileReader fr = new FileReader ("read_text.txt");
FileWriter fw = new FileWriter ("write_text.txt");

int read ;

while ( (read=fr.read()) != -1)
{
fw.write(read);
}
fw.close();
}catch (IOException e)
[/java]

And voila , the file is ready with the data in it as well.

So, what we have done until now is to understand how to read character data from the file and write it back to another file. We can take this one notch up further and do the same using BufferedReader. Ask in your Java Training class why BufferedReader is more efficient than the simple FileReader. Also using BufferedReader class, we are going to read one line at a time, which we can read comfortably.

Now, let’s try and write back the contents of a file to a new file write_text.txt using BufferedReader which can read Lines instead of characters.

[java title=”CharacterStream.java” gutter=”true” highlight=”10″]
package com.wonder;

import java.io.*;

public class HelloWorld  {

public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuilder file_text = new StringBuilder();
String temp;

try
{
FileReader fr = new FileReader("read_text.txt");
BufferedReader br = new BufferedReader ( fr);

//read each line of the file
while ( ( temp = br.readLine()) != null)
{
file_text.append(temp);
}
} catch (IOException e)
{
System.out.println (" Error during file read -> " + e);
}

System.out.println ("The contents of the file are n" + file_text);

try
{
FileWriter fw = new FileWriter ("write_text.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write (file_text.toString());

} catch (IOException e)
{
System.out.println ("Error during file write -> " + e);
}

System.out.println ("I wrote the file write_text.txt");
}
}

[/java]

** FileWriter and FileReader classes in Java are ONLY meant for reading character files. Ask your Java Training instructor to explain more.

Does this do the trick ? Let’s see, the file write_text.txt has been created. However, as you can see from the hover text, the file does not have any data. Why is that ?

As we have seen before, always stream writers need to be explicitly closed.  Close the BufferedWriter handle.

[java title=”HelloWorld.java” gutter=”true” highlight=”6″]
try
{
FileWriter fw = new FileWriter ("write_text.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write (file_text.toString());
bw.close();

} catch (IOException e)
[/java]

Now, answer the following questions

Question 1 : What happens if a file already exists ? Will BufferedWriter.write() method overwrite the file or make a copy ?

Question 2 : What happens if the file has more than one line of text ? Will it read all the files ?

Question 3 : How do you modify the program to read the text line by line and write the text into the write_text.txt file preserving the new lines. ( Read, How to get the default new line character in Java )

Now how about reading binary files ? Say excel files, images, .dat files etc. Ask in your Java Training class what is the difference between binary files and text files if you are not clear.

[java title=”FileOpenClass.java” gutter=”true” highlight=”6″]
//Import the I/O java library
import java.io.*;
/*
* This program will explain the difference between
* FileReader and FileInputStream
*
*/

public class FileOpenClass{

public static void main(String[] args) {
// We will use the FileReader object in the java.io
// library to read the file

StringBuffer sb;

//
try {
FileReader fr = new FileReader ("Stream1.xlsx");
FileWriter fw = new FileWriter ("Stream2.xlsx");

int read ;

while ( (read=fr.read()) != -1)
{
fw.write(read);
}
fw.close();
}catch (IOException e)
{
System.out.println ( "Could not read file -> " +e );
}

//Now try reading the Stream2.xlsx. Will it read ?

try {
InputStream is = new FileInputStream ("Stream1.xlsx");
OutputStream os = new FileOutputStream ("Stream3.xlsx");

int read ;

while ( (read= is.read()) != -1)
{
os.write(read);
}
os.close();
}catch (IOException e)
{
System.out.println ( "Could not read file -> " +e );
}
//Now Try reading the Stream3.xlsx. Will it read ?

}
}
[/java]

Question 4 : Now explain the difference between FileReader class and FileInputStream class ? When each should be used.

Question 5 : If you wanted to read the file “D:dataStream1.xlsx” , how should you write your FileInputStream statement ?

Question 6 : Modify the program so that the program can read the file from any OS/Architecture ? How would you know what the file Separator is ?

Hint: File.Separator

[java title=”FileOpenClass.java” gutter=”true” highlight=”6″]
//Import the I/O java library
String fileSeparator = System.getProperty("file.separator");
try {
InputStream is = new FileInputStream ("D:"+fileSeparator + "data" + fileSeparator + "Stream1.xlsx");
OutputStream os = new FileOutputStream ("Stream3.xlsx");

int read ;

while ( (read= is.read()) != -1)
{
os.write(read);
}
os.close();
}catch (IOException e)
{
System.out.println ( "Could not read file -> " +e );
}
[/java]

asdf

Advertisements

2 thoughts on “Java I/O

  1. Galen says:

    Hello excellent blog! Does running a blog similar to this require
    a massive amount work? I’ve very little understanding of coding but I had been hoping to start my own blog in the near
    future. Anyhow, should you have any ideas or tips for new blog
    owners please share. I understand this is off topic but I just wanted to ask.
    Many thanks!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s