Previous
Index



Objective 5, FileInputStream,OutputStream and RandomAccessFile

Write appropriate code to read, write and update files using FileInputStream, FileOutputStream, and RandomAccessFile objects.

FileInputStream and FileOutputStream

The following example creates a text file called Out.txt and writes the text Hello into it. If you type out the resulting file you will see that file comes out as H e l l o (with a gap between each letter) . I suspect this is because a character is 16 bits and because ASCII is 8 bit, the upper 8 bits result in a blank character.


This also illustrates the previous objective in that it uses the FilterOutputStream descendent DataOutputStream. This allows human readable chars to be written. If this example only used FileOutputStream methods you would be limited to writing bytes or ints. If you do this and then type the results to the console, it just shows up as junk characters.

import java.io.*;

public class Fos{
                    String s = new String("Hello");
                    public static void main(String argv[]){
                    Fos f = new Fos();
                    f.amethod();
                   }



            public void amethod(){
                try{
                FileOutputStream fos = new FileOutputStream("Out.txt");
                //DataOutputStream allows you to write chars
                DataOutputStream dos = new DataOutputStream(fos);
                dos.writeChars(s);
                }catch(IOException ioe) {}
              }
}

The following example will read the text file produced by the last example and output the text to the console. Note that because the previous program will have written Out.txt as unicode, if you create a text file with an editor containing a a string such as "Hello" , the following code will probably print out junk such as question marks.

import java.io.*;

public class Fis{
                 public static void main(String argv[]){
                 Fis f = new Fis();
                 f.amethod();
                }


      public void amethod(){
                try{
                FileInputStream fis = new FileInputStream("Out.txt");
                DataInputStream dis = new DataInputStream(fis);
                while(true){
                    char c =dis.readChar();
                    System.out.println(c);
                    }
                }catch(IOException ioe) {}              
          }
}
       

RandomAccessFile

The RandomAccessFile class is way out on it's own and doesn't fit neatly with the Stream I/O classes. If you get answer possibilities that mix instances of RandomAccessFile with other streams, then they are almost certainly the wrong answers. RandomAccessFile is more like the File class than the Stream classes. It is useful if you want to move backwards and forwards with in a file without re-opening it.

For its constructor RandomAccessFile takes either an instance of a File class or a string and a read/write mode argument. The mode argument can be either "r" for read only or "rw" can be read and written to. Memorise those two options, don't get caught out in the exam by a bogus mode such as "w", "ro" or "r+w";

Unlike the File class, if you attempt pass the name of a file as a constructor, RandomAccessFile will attempt to open that file. If you pass only the "r" parameter mode and the file does not exist an exception will be thrown. If you pass the mode as "rw" RandomAccessFile will attempt to create the file in the underlying operating system.

The Random Access does not take a stream as a constructor parameter.


This example will read the Out.txt file created by the Fos.java example shown earlier.

Because of the blank high byte (not bit), the results show a question mark with each letter.

import java.io.*;

public class Raf{
               public static void main(String argv[]){
                 Raf r = new Raf();
                 r.amethod();
                 }


            public void amethod(){
                 try{
                RandomAccessFile raf = new RandomAccessFile("Out.txt","rw");
                for(int i=0; i<10;i++){
                                raf.seek(i);
                                char myc = raf.readChar();
                                //?Show for high bytes
                                System.out.println(myc);
                                }
                        } catch(IOException ioe) {}         
              }
}
    
   

Questions

Question 1)

Assuming any exception handling has been set up, which of the following will create an instance of the RandomAccessFile class?

1) RandomAccessFile raf = new RandomAccessFile("myfile.txt","rw");
2) RandomAccessFile raf = new RandomAccessFile( new DataInputStream());
3) RandomAccessFile raf = new RandomAccessFile("myfile.txt");
4) RandomAccessFile raf = new RandomAccessFile( new File("myfile.txt"));


Question 2)

Which of the following statements are true?

1) The RandomAccessFile class allows you to move forwards and backwards without re-opening the file
2) An instance of RandomAccessFile may be used as a constructor for FileInputStream
3) The methods of RandomAccessFile do not throw exceptions
4) Creating a RandomAccessFile instance with a constructor will throw an exception if the file does not exist.


Question 3)

Which of the following statements are true?

1) The FileInputStream can take either the name of a file or a an instance of the File class as a constructor
2) FileInputStream will throw an exception if the file name passed as a constructor does not exist
3) The methods of the FileInputStream are especially appropriate for manipulating text files
4) The delete method of the FileOutputStream class will remove a file from the operating system


Question 4)

Question 4)

What will happen when you attempt to compile and run the following code

import java.io.*;
public class Fos{
                    String s = new String("Hello");
                    public static void main(String argv[]){
                    Fos f = new Fos();
                    f.amethod();
                   }

                 public void amethod(){
                        FileOutputStream fos = new FileOutputStream("Out.txt");
                        fos.write(10);
              }
}


1) Compile time error
2) Runtime error
3) Creation of a file called Out.txt containing the text "10"
4) Creation of a file called Out.txt


Question 5)

Which of the following statements are true?

1) The seek method of FileInputStream will set the position of the file pointer
2) The read method of FileInputStream will read bytes from a FileInputStream
3) The get method of FileInputStream will read bytes from a FileInputStream
4) A FileOutputStream can be closed using the close method

Answers

Answer to Question 1)

1) RandomAccessFile raf = new RandomAccessFile("myfile.txt","rw");

The RandomAccessFile is an anomaly in the Java I/O architecture. It descends directly from Object and is not part of the Streams architecture.

Answer to Question 2

1) The RandomAccessFile class allows you to move forwards and backwards without re-opening the file
4) Creating a RandomAccessFile instance with a constructor will throw an exception if the file does not exist

Answer to Question 3)

 1) The FileInputStream can take either the name of a file or a an instance of the File class as a constructor
2) FileInputStream will throw an exception if the file name passed as a constructor does not exist
Option 3 is a reasonable description of the Reader and Writer classes, the FileInput and Output clases are designed to read and write bytes rather than text.

Answer to Question 4)

1) Compile time error

This code will throw an error something like

Fos.java:10: Exception java.io.IOException must be caught, or it must be declare in the throws clause of this method. FileOutputStream fos = new FileOutputStream("Out.txt");

Answer to Question 5)

2) The read method of FileInputStream can be used to read bytes from a FileInputStream
4) A FileOutputStream can be closed using the close method

Option one referring to a seek method is fairly implausible as the concept of file pointer is appropriate to the RandomAccessFile rather than the stream classes. The get method of option three is implausible as the prefix get is almost always followed by what you are getting. 


Other sources on this topic

This topic is covered in the Sun Tutorial at
http://java.sun.com/docs/books/tutorial/essential/io/

The JLS on Java IO a bit academic and bare
www.infospheres.caltech.edu/resources/langspec-1.0/javaio.doc.html

Java I/O by Elliotte Rusty Harold
Oreilly have published this book specifically about Java I/O It probably goes into more detail than is necessary for the Certification exam but browsing the online samples might give you some insights. The book gets generally good reviews at www.amazon.com
http://www.oreilly.com/catalog/javaio

Joyothi has some handy tables for the I/O classes at
http://www.geocities.com/SiliconValley/Network/3693/io.html






Previous
Index