Programming Java Tutorial – input / output
January 23, 2009 at 4:19 pm Leave a comment
We also have some excellent Beginners Programming Java tutorials that use high quality narrated videos and practical working files to teach the fundamentals of programming in Java Beginners Java Tutorial CD
Java Tutorial – Input / Output
The code below is based on Java 1.6 – some syntax may differ for previous versions.
Receiving and sending data to and from an external source is something that you will likely have to do regularly as your programs develop. Java provides a number of classes and libraries to facilitate this process. In this tutorial we will concentrate on reading from and writing to external text files.
To send and receive data in Java, we use output and input ‘streams’. There are various resources within the Java language to interface with input and output streams in your programs, many of them suited to different types of programming tasks. This Java Tutorial will demonstrate a few of the more likely options for use within basic applications.
Java – Reading from a file
Create a new Java project in your IDE and add the following import statements at the top of your main class:
//input/ output imports import java.io.*; import java.util.*;
These imports contain the classes that we will use for our I/O operations: the first of these classes will be FileReader and Scanner. In the first example, we will read the text from a text file into our program one line at a time. Enter the following code in your main method:
//try block in case of IO exceptions
try
{
//create filereader, passing filename
String filename = "sometext.txt";
FileReader fr = new FileReader(filename);
//pass filereader to scanner
Scanner scan = new Scanner(fr);
//loop through the file content
while(scan.hasNextLine())//check that there is more
{ System.out.println(scan.nextLine()); }
//close the input stream
scan.close();
fr.close();
}
//an exception has been thrown
catch(IOException ioe)
{
//output the details
System.out.println(ioe);
ioe.printStackTrace();
}
The code has to be included in try/catch blocks because, when your program relies on external input, there is always a risk of unforeseen error, such as problems with the external file. Placing your code within the try block allows your program to continue functioning when these problems occur, and provides you with the ability to decide what should happen if the I/O processing goes wrong. This is the function of the catch block, so you should place here whatever you want the program to do on encountering such an error, as this is where the code will jump to when that happens.
Before compiling your program, you will need to create the file for reading. Open a text editor (such as notepad/ notepad++) and enter the following:
Outside of a book A dog is a man's best friend Inside of a dog It's too dark to read
Save your file with the name ‘sometext.txt’ in the same directory within your workspace as the new project; for example, on Windows, if the project is called AProject and your workspace directory is C:\Workspace save the file in the C:\Workspace\AProject directory. If you look at the first line of code in the try block, you’ll see that the filename given is a relative URL, i.e. it does not have a drive listed as part of it; you can also use the class with an absolute URL if you need to.
NB: If you’re using Eclipse you can find out your workspace location by choosing Project > Properties.
Now compile and run the program, you should see the contents of the file written a line at a time to the output console. What’s happening here is that the program is opening an input stream (according to the filename given) with the FileReader. The Scanner then processes the data from the stream, and can do this in a variety of ways, reading a line, a number or a byte at a time. Although our program merely outputs the data read in, once it’s in your program you can do whatever you need to with it, for example by assigning it to variables.
To demonstrate the purpose of the try and catch blocks, change the filename in the code so that it doesn’t match the actual file (e.g. String filename = “bla.txt”;) and run your program again. You’ll see the effect of the exception being thrown in your output console – this is because the program couldn’t find the file specified. (Remember to change the filename back afterwards.)
Using the Scanner, as above, makes text processing easier if you’re reading chunks of the text, however you can use the FileReader itself to read the file in a character at a time if this suits your needs. Processing data through the FileReader in this way is a little more complex, as the contents of the file are in the form of individual characters, including the newlines and end of file:
//create FileReader
FileReader fRead = new FileReader(filename);
//keep track of whether end of file reached
boolean end = false;
//loop through file characters
while(!end)
{
//read the next character (as an int)
int ch = fRead.read();
//-1 represents the end of file
if(ch==-1)
end=true;
else
{
//write the character out
char chr = (char)ch;
System.out.print(chr);
}
}
//close the stream
fRead.close();
Run the program, it should have the same effect as the previous code.
Writing to a file in Java
The process for writing to files is similar, again, try and catch blocks are required and this time an output stream is opened. However, if your program cannot find the file specified to write to in the relevant directory, it will create it. If the file does exist the below methods will replace its contents. The first method writes to an output file using the FileWriter class, which can write a specified section of a string (in this case it should write ‘defg’); enter the following in your try block:
//write out using FileWriter
FileWriter fw = new FileWriter("output1.txt");
//write specified section of string
fw.write("abcdefghijkl", 3, 4);
fw.close();
Check your workspace project directory to see if the output1.txt has been created and written to.
The next example uses the PrintWriter class to write to the file; demonstrating two approaches to inserting newlines:
//write out using PrintWriter
PrintWriter pw = new PrintWriter("output2.txt");
//using println to insert newline at end
pw.println("Some text I'd like to write to a file");
pw.println("And some more");
//use print - insert newline explicitly (\r\n)
pw.print("Yet more I'd like to write to a file\r\n" +
"And more again.");
pw.close();
Again, check the appropriate directory for the output2.txt file; it should contain 4 lines of text.
Your programs will likely involve a range of different approaches to Input/Output depending on their particular requirements, so it is worth spending a little time familiarising yourself with the various options that Java provides.
Entry filed under: Java. Tags: Beginners Java Programming, Java, Java Programming.

Trackback this post | Subscribe to the comments via RSS Feed