cstutoringcenter.com logo

E-mail:    Password:    

Become a premier member today to gain access to exclusive member benefits! Just $10.00 to join FOR LIFE!

halls of valhalla

<< Tutorial 10
Tutorial 12 >>
Java tutorial index

Java File Input/Output

Tutorial 11

Register or log in today to rate this tutorial!
Current ranking: / 5 stars with 19 votes.

File Input
File Output
Example 1
Example 2

Just the same as C++, you can read and write from text files in Java.

File Input

In Java, file input occurs through whats called a BufferedReader. The BufferedReader is contained in the java.io library.

There are numerous types of input streams in Java such as Character Streams, Byte Streams and Object Streams just to name some. The commonality of these mentioned streams is that they use the operating system directly to handle the stream.

A BufferedReader will greatly reduce the operating systems use when reading or writing from files. A simple BufferedReader is defined below:

BufferedReader varName = new BufferedReader(
      new FileReader("filename.txt"));

where in the above definition, varName is a useful name of the BufferedReader input stream; and filename.txt is an input text file.

The rule about the input stream is that it MUST be contained in a try catch block. Here is how that will look in a short code snippet:

   BufferedReader br;
   br = new BufferedReader(new FileReader("input.txt"));

   //rest of reading code here

}catch(Exception e){

Example 1:
File input example

Download source code here (Right click - Save Tagret As...)

Download input file here (Right click - Save Tagret As...)

Here is a short example that will read a file of integers and compute the average. It will use a StringTokenizer to split the integers apart which will be separated by a white space.

import java.io.*;
import java.util.*;

public class InputExample{

   public static void main(String args[]){
        StringTokenizer st;

           BufferedReader br = new BufferedReader(
                     new FileReader("input1.txt"));

           String line = br.readLine();
           double avg = 0.0;
           int num = 0, count = 0;

           while(line != null){
                   st = new StringTokenizer(line);

                   for(int i = 0; i < st.countTokens(); i++){
                           avg += Double.parseDouble(st.nextToken());
                   line = br.readLine();


           avg = avg/count;
           System.out.println("Avg: " + avg);

        }catch(Exception e){}
   } //main
} //class

The output from above is: "Avg: 26.5"

The program also uses some methods from the StringTokenizer class. If you need a refresher, please see tutorial 6.

Here is an explanation of the two methods used above in the BufferedReader class.

String readLine()

This will extract an entire line of text as denoted by the carriage return character '\r' or a new line character '\n'. In the above program, the line was placed in a String variable called line.

void close()

This will simply flush the input stream and close the file.

int read()

There is also another method in the class called read(). This will simply read an individual character. It will return a -1 if the end of the stream has been reached.

File Output

In Java, file output occurs through what's called a BufferedWriter. The BufferedWriter is contained again in the java.io library.

Here is the simple definition of a BufferedWriter object:

BufferedWriter varName = new BufferedWriter(
      new FileWriter("filename.txt"));

For the BufferedWriter class, if the output file name is not currently in the directory, it will create the file for you. If the file is already there, the output will overwrite the information in the output file.

Let's see another program that will write output to a file.

Example 2:
File output example

Download source code here (Right click - Save Tagret As...)

Here is a short example that will write a String to a text file named output.txt. It requires a command line argument which will be a String argument.

import java.io.*;
public class OutputExample{

   public static void main(String args[]){

        if(ars.length == 0){
          System.out.println("String argument needed.");

        String word = args[0];

           BufferedWriter bw = new BufferedWriter(
                     new FileWriter("output.txt"));

           String ans = "";

           for(int i = 0; i < word.length(); i++){
               ans += word.substring(i);
               ans = "";


        }catch(Exception e){}
   } //main
} //class

There is no output to the console in this program. It is only in the output file.

For the purpose of the example, the String "hello there" will be used. This will be the output in the file:

hello there
ello there
llo there
lo there
o there

Let's observe some methods that are used from the BufferedWriter class:

void write(String s)

This will write a String argument to the file.

void newLine()

This will write a line separator to the file. This is not quite the new line character but it can be thought of that way.

void close()

This will simply close the file output stream.

<< Tutorial 10
Tutorial 12 >>
Java tutorial index


Please feel free to leave a comment! Just keep it peaceful is all we ask and try to be as informative as possible to help others. Spam will NOT be tolerated!

Reviewing C++

Reviewing C++

Print: $39.99

Reviewing Java

Reviewing Java

Print: $34.99