home *** CD-ROM | disk | FTP | other *** search
/ Java Certification Exam Guide / McGrawwHill-JavaCertificationExamGuide.iso / pc / Web Links and Code / code / chap11 / Ran.java < prev   
Encoding:
Java Source  |  1997-04-20  |  1.3 KB  |  55 lines

  1. import java.io.*;
  2.  
  3. class Ran {
  4.    static String fileName = "Ran.test";
  5.  
  6.    public static void main(String[] args) {
  7.      try {
  8.         sayHello();
  9.         appendHi();
  10.         readGreeting();
  11.      } catch (IOException x) {
  12.         System.out.println(x.getMessage());
  13.      }
  14.    }
  15.  
  16.    public static void sayHello() throws IOException {
  17.       DataOutputStream ds = null;
  18.       try {
  19.          File f = new File(fileName);
  20.          FileOutputStream out = new FileOutputStream(f);
  21.          ds = new DataOutputStream(out);
  22.          ds.writeBytes("hello!");
  23.       } finally {
  24.          if (ds != null)
  25.             ds.close();
  26.       }
  27.    }
  28.  
  29.    public static void appendHi() throws IOException {
  30.       RandomAccessFile out = null;
  31.       try {
  32.          File f = new File(fileName);
  33.          out = new RandomAccessFile(f, "rw");
  34.          out.seek(out.length());
  35.          out.writeBytes(" hi!");
  36.       } finally {
  37.          if (out != null)
  38.             out.close();
  39.       }
  40.    }
  41.  
  42.    public static void readGreeting() throws IOException {
  43.       RandomAccessFile in = null;
  44.       try {
  45.          File f = new File(fileName);
  46.          in = new RandomAccessFile(f, "r");
  47.          String s = in.readLine();
  48.          System.out.println(s);
  49.       } finally {
  50.          if (in != null)
  51.             in.close();
  52.       }
  53.    }
  54. }
  55.