IOTest.java

This example deals with File, FileInputStream, DataOutputStream, RandomAccessFile. Play with it, try to understand every bit of the output.
import java.io.*;
public class IOTest {
  public static void main (String[] args)throws IOException{
    int n = 0x11223344;
    String s = "Hello";
      
    // write them out
    DataOutputStream dos = new DataOutputStream(new FileOutputStream("t.txt"));
      
    // If you want to append instead of overrite
    //DataOutputStream dos = new DataOutputStream(new FileOutputStream("t.txt", true));
      
    dos.writeInt(n);
    dos.writeChars(s);// unicode, two byte/char
    dos.close();
      
    File f = new File("t.txt");
    
    FileInputStream fis = new FileInputStream(f);
    byte[] ba = new byte[(int)f.length()];
    
    // read the whole file back as byte array
    fis.read(ba);
    for (int i = 0; i< f.length(); i++) {
      // print one byte/line
      // can you interpret the results?
      System.out.println(ba[i]);
    }
    fis.close();
      
    //random access file is different
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    // skip the interger 
    raf.seek(4);
    
    // Read one ascii letter a time, skip the space
    for (int i = 0; i < (raf.length()-4)/2; i++) {
       System.out.println(raf.readChar());
    }
    raf.writeChars(" Are you OK?"); // unicode, two byte/char
    
    // skip the interger 
    raf.seek(4);
      
    //unicode magic, 2 byte/char
    System.out.println(raf.readLine()); // " H e l l o   A r e   y o u   O K ?"

    System.in.read();           
  }
}

last updated: 01-16-2001
Copyright © 1999 - 2003 Roseanne Zhang, All Rights Reserved
[ Java certification page] [ SCJP FAQ] [ JavaChina]