Home > Computer Programming > Using Files in Java

Using Files in Java

This week we are going to begin working with files in Java. The objectives are to learn how to:

  1. Read from a text file.
  2. Write to a text file.

Start by creating a new project in NetBeans called ReadFromFile. Use the code below to create your main routine.


package readfromfile;
import java.io.*;

public class ReadFromFile {

  public static void main(String[] args) {
    BufferedReader reader = new BufferedReader(new FileReader("c:\\in.txt"));
    String s = reader.readLine();
    System.out.println("The file contains:" + s);
    reader.close();
  }
}

This code causes compile errors. We will discuss the cause of these in class.

Now you will create your own project in NetBeans called WriteToFile. Your aim is to create a file and add a message to it. Use the code below to get you started. You will need to fix the compile errors in the same way as before, and you will need to look up how to write output to the file in the online Java API.


package readfromfile;
import java.io.*;

public class WriteToFile {

  public static void main(String[] args) {
    PrintWriter writer = new PrintWriter(new FileWriter("c:\\out.txt"));
    // Add a line here which writes a message to the file.
    // You will have to look up PrintWriter in the Java API.
    System.out.println("The file contains:" + s);
    writer.close();
  }
}

Finally, create a third project in NetBeans called ReadFromFileLoop. Edit your in.txt file so that it contains several lines of text. Your task is to work out how to read the file line by line, not all in one go. You will need to set up a loop to do this.

  • What are you going to do each time the loop runs?
  • What is the condition that keeps the loop going?
  • What is the condition that makes the loop stop?
  • What type of loop do you need?

You may have noticed that dealing with text files in Java is a bit fiddly. As an extension task, create your own Java class that you can reuse in projects that involve reading from and writing to text files. It might be something like this:

class FileIO {
   void setInputFileName(String s){}
   void setOutputFileName(String s){}
   void writeLine(String s){}
   String readLine(){}
 }

You could also add a method to return the contents of the input file as an array of Strings.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

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