Home  Listings  By Name  By Subject  Email  www.tomswan.com  Help 

Java 2 Just Click! Solutions

Chapter 24 Listings

© 2001 by Tom Swan. All rights reserved. Updated: 6/4/01 12:20:54 PM

Return to Listings page
Switch to Solutions by name page
Switch to Solutions by subject page


Listing 24-1 ReadLine/ReadLine.java Page 557

Return to top
001: import java.io.*;
002: 
003: public class ReadLine {
004: 
005:  // Input a string
006:  public static String readLine()
007:   throws IOException {
008:   BufferedReader br = 
009:    new BufferedReader(new InputStreamReader(System.in));
010:   return br.readLine();
011:  }
012: 
013:  // Prompt for and input a string
014:  public static String readLine(String prompt)
015:   throws IOException {
016:   System.out.print(prompt);
017:   return readLine();
018:  }
019: 
020:  // Main program
021:  public static void main(String args[])
022:   throws IOException {
023:   System.out.println("Enter strings when prompted.");
024:   System.out.print("Enter your first name: ");
025:   String s1 = readLine();
026:   String s2 = readLine("Enter your last name: ");
027:   System.out.println("Your name: " + s1 + " " + s2);
028:  }
029: }
Return to top

Listing 24-2 Directory/Directory.java Page 561

Return to top
001: import java.io.*;
002: 
003: public class Directory {
004: 
005:  // Input a string
006:  public static String readLine()
007:   throws IOException {
008:   BufferedReader br = 
009:    new BufferedReader(new InputStreamReader(System.in));
010:   return br.readLine();
011:  }
012: 
013:  // Prompt for and input a string
014:  public static String readLine(String prompt)
015:   throws IOException {
016:   System.out.print(prompt);
017:   return readLine();
018:  }
019: 
020:  // Construct File object for directory path
021:  public static File getFileForPath(String path)
022:   throws IOException {
023:   File dir = new File(path);
024:   if (!dir.isDirectory())
025:    throw new IOException("Not a directory");
026:   return dir;
027:  }
028: 
029:  // Main program method
030:  public static void main(String args[]) {
031:   String path;
032:   try {
033:    // Get pathname from command line or prompt user
034:    if (args.length > 0)
035:     path = args[0];
036:    else
037:     path = readLine("Path name? ");
038:   // List directory
039:    File dir = getFileForPath(path);
040:    String[] filenames = dir.list();
041:    for (int i = 0; i < filenames.length; i++)
042:     System.out.println(filenames[i]);
043:   } catch (IOException e) {            // Trap exception
044:    System.err.println(e.toString());   // Display error
045:   }
046:  }
047: }
Return to top

Listing 24-3 FileInfo/FileInfo.java Page 563

Return to top
001: import java.io.*;
002: import java.util.Date;
003: 
004: public class FileInfo {
005: 
006:  // Input a string
007:  public static String readLine()
008:   throws IOException {
009:   BufferedReader br = 
010:    new BufferedReader(new InputStreamReader(System.in));
011:   return br.readLine();
012:  }
013: 
014:  // Prompt for and input a string
015:  public static String readLine(String prompt)
016:   throws IOException {
017:   System.out.print(prompt);
018:   return readLine();
019:  }
020: 
021:  // Construct File object for named file
022:  public static File getFileForFilename(String filename)
023:   throws IOException {
024:   File fi = new File(filename);
025:   // Do not move the following statements;
026:   // order is critical
027:   if (!fi.exists())
028:    throw new IOException("File not found");
029:   if (!fi.isFile())
030:    throw new IOException("Not a file");
031:   return fi;
032:  }
033: 
034:  // Show a labeled string
035:  public static void showLabel(String label, String s) {
036:   System.out.print(label);
037:   System.out.println(s);
038:  }
039: 
040:  // Display information about file fi
041:  public static void showInformation(File fi) {
042:   showLabel("Path     = ", fi.getPath());
043:   showLabel("Filename = ", fi.getName());
044:   showLabel("Length   = ",
045:    new Long(fi.length()).toString());
046:   showLabel("Readable = ", 
047:    new Boolean(fi.canRead()).toString());
048:   showLabel("Writable = ", 
049:    new Boolean(fi.canWrite()).toString());
050:   showLabel("Modified = ",
051:    new Date(fi.lastModified()).toString());
052:  }
053: 
054:  // Main program method
055:  public static void main(String args[]) {
056:   String filename;
057:   try {
058:    // Get pathname from command line or prompt user
059:    if (args.length > 0)
060:     filename = args[0];
061:    else
062:     filename = readLine("File name? ");
063:    File fi = getFileForFilename(filename);
064:    showInformation(fi);
065:   } catch (IOException e) {            // Trap exception
066:    System.err.println(e.toString());   // Display error
067:   }
068:  }
069: }
Return to top

Listing 24-4 FilterDir/FilterDir.java Page 565

Return to top
001: import java.io.*;
002: 
003: // File filter class
004: class FilterClass implements FilenameFilter {
005:  public boolean accept(File dir, String name) {
006:   File f = new File(dir, name);
007:   if (f.isDirectory())
008:    return true;
009:   else
010:    return false;
011:  }
012: }
013: 
014: public class FilterDir {
015: 
016:  // Input a string
017:  public static String readLine()
018:   throws IOException {
019:   BufferedReader br = 
020:    new BufferedReader(new InputStreamReader(System.in));
021:   return br.readLine();
022:  }
023: 
024:  // Prompt for and input a string
025:  public static String readLine(String prompt)
026:   throws IOException {
027:   System.out.print(prompt);
028:   return readLine();
029:  }
030: 
031:  // Construct File object for directory path
032:  public static File getFileForPath(String path)
033:   throws IOException {
034:   File dir = new File(path);
035:   if (!dir.isDirectory())
036:    throw new IOException("Not a directory");
037:   return dir;
038:  }
039: 
040:  // Main program method
041:  public static void main(String args[]) {
042:   String path;
043:   try {
044:    // Get pathname from command line or prompt user
045:    if (args.length > 0)
046:     path = args[0];
047:    else
048:     path = readLine("Path name? ");
049:    File dir = getFileForPath(path);
050:    String[] filenames = dir.list(new FilterClass());
051:    for (int i = 0; i < filenames.length; i++)
052:     System.out.println(" " + filenames[i]);
053:   } catch (IOException e) {            // Trap exception
054:    System.err.println(e.toString());   // Display error
055:   }
056:  }
057: }
Return to top

Listing 24-5 CopyFile/CopyFile.java Page 568

Return to top
001: import java.io.*;
002: 
003: public class CopyFile {
004:  
005:  // Input a string
006:  public static String readLine()
007:   throws IOException {
008:   BufferedReader br = 
009:    new BufferedReader(new InputStreamReader(System.in));
010:   return br.readLine();
011:  }
012: 
013:  // Prompt for and input a string
014:  public static String readLine(String prompt)
015:   throws IOException {
016:   System.out.print(prompt);
017:   return readLine();
018:  }
019: 
020:  // Construct File object for named file
021:  public static File getFileForFilename(
022:   String filename, boolean checkExistence)
023:   throws IOException {
024:   File fi = new File(filename);
025:   if (checkExistence) {
026:    // Do not move the following statements;
027:    // order is critical
028:    if (!fi.exists())
029:     throw new IOException(fi.getName() + " not found");
030:    if (!fi.isFile())
031:     throw new IOException(fi.getName() + " is not a file");
032:   }
033:   return fi;
034:  }
035:  
036:  // Returns true if user answers yes to prompt 
037:  public static boolean yes(String prompt)
038:   throws IOException {
039:   System.out.print(prompt);
040:   char ch = (char)System.in.read();
041:   if (ch == 'y' || ch == 'Y') {
042:    return true;
043:   }
044:   return false;
045:  }
046:  
047:  // Copy and old file to a new one
048:  // Overwrites or creates the new file
049:  public static void copy(File fileOld, File fileNew)
050:   throws IOException {
051:   FileInputStream fin = new FileInputStream(fileOld);
052:   FileOutputStream fout = new FileOutputStream(fileNew);
053:   System.out.println("Copying...");
054:   int b = fin.read();
055:   while (b != -1) {
056:    fout.write(b);
057:    b = fin.read();
058:   }
059:   System.out.println("Finished");
060:  }
061:  
062:  // Main program method
063:  public static void main(String args[]) {
064:   String fileOldName, fileNewName;
065:   File fileOld, fileNew;
066:   try {
067:    if (args.length >= 2) {
068:     fileOldName = args[0];
069:     fileNewName = args[1];
070:    } else {
071:     fileOldName = readLine("Copy what file? ");
072:     fileNewName = readLine("To what file? ");
073:    }
074:    fileOld = getFileForFilename(fileOldName, true);
075:    fileNew = getFileForFilename(fileNewName, false);
076:    if (fileNew.isDirectory())
077:     throw new IOException(
078:      fileNew.getName() + " is a directory");
079:    if (fileNew.exists()) {
080:     if (!yes("Overwrite file " + fileNew.getName() + "? "))
081:      throw new IOException("File not copied");
082:    } else {
083:     if (!yes("Create new " + fileNew.getPath() + "? "))
084:      throw new IOException("File not copied");
085:    }
086:    copy(fileOld, fileNew);
087:   } catch (IOException e) {            // Trap exception
088:    System.err.println(e.toString());   // Display error
089:   }
090:  }
091: }
Return to top

Listing 24-6 ReadText/ReadText.java Page 573

Return to top
001: import java.io.*;
002: 
003: public class ReadText {
004: 
005:  // Input a string
006:  public static String readLine()
007:   throws IOException {
008:   BufferedReader br = 
009:    new BufferedReader(new InputStreamReader(System.in));
010:   return br.readLine();
011:  }
012: 
013:  // Prompt for and input a string
014:  public static String readLine(String prompt)
015:   throws IOException {
016:   System.out.print(prompt);
017:   return readLine();
018:  }
019: 
020:  // Construct File object for named file
021:  public static File getFileForFilename(String filename)
022:   throws IOException {
023:   File fi = new File(filename);
024:   // Do not move the following statements;
025:   // order is critical
026:   if (!fi.exists())
027:    throw new IOException(fi.getName() + " not found");
028:   if (!fi.isFile())
029:    throw new IOException(fi.getName() + " is not a file");
030:   return fi;
031:  }
032:  
033:  // Main program method
034:  public static void main(String args[]) {
035:   String filename;
036:   try {
037:    // Get pathname from command line or prompt user
038:    if (args.length > 0)
039:     filename = args[0];
040:    else
041:     filename = readLine("Read what text file? ");
042:    File fi = getFileForFilename(filename);
043:    FileInputStream fin = new FileInputStream(fi);
044:    BufferedReader bin = 
045:     new BufferedReader(new InputStreamReader(fin));
046:    String line = bin.readLine();  // Read first line
047:    while (line != null) {         // Loop until end of file
048:     System.out.println(line);     // Print current line
049:     line = bin.readLine();        // Read next line
050:    }
051:   } catch (IOException e) {            // Trap exception
052:    System.err.println(e.toString());   // Display error
053:   }
054:  }
055: }
Return to top

Listing 24-7 WriteData/WriteData.java Page 575

Return to top
001: import java.io.*;
002: import java.util.Random;
003: 
004: public class WriteData {
005: 
006:  // Main program method
007:  public static void main(String args[]) {
008:   // Instance variables
009:   int dataSize = 10;
010:   Random gen = new Random();
011:   try {
012:    // Create file objects
013:    FileOutputStream fout = new FileOutputStream("Data.bin");
014:    BufferedOutputStream bout = new BufferedOutputStream(fout);
015:    DataOutputStream dout = new DataOutputStream(bout);
016:    // Write data to file in this order:
017:    // 1. number of data elements
018:    // 2. elements
019:    dout.writeInt(dataSize);
020:    for (int i = 0; i < dataSize; i++) {
021:     dout.writeDouble(gen.nextDouble());
022:    }
023:    dout.flush();
024:    fout.close();
025:    System.out.println(dout.size() + " bytes written");
026:   } catch (IOException e) {            // Trap exception
027:    System.err.println(e.toString());   // Display error
028:   }
029:  }
030: }
Return to top

Listing 24-8 ReadData/ReadData.java Page 577

Return to top
001: import java.io.*;
002: 
003: public class ReadData {
004: 
005:  // Main program method
006:  public static void main(String args[]) {
007:   // Instance variables
008:   int dataSize;
009:   double data[];
010:   try {
011:    // Create file objects
012:    FileInputStream fin = new FileInputStream("Data.bin");
013:    BufferedInputStream bin = new BufferedInputStream(fin);
014:    DataInputStream din = new DataInputStream(bin);
015:    // Read data from file in this order:
016:    // 1. number of data elements
017:    // 2. elements
018:    dataSize = din.readInt();     // Get number of elements
019:    data = new double[dataSize];  // Create array for data
020:    // Read elements into array
021:    for (int i = 0; i < dataSize; i++) {
022:     data[i] = din.readDouble();  // Read each element
023:    }
024:    fin.close();
025:    // Display results:
026:    System.out.println("/n" + dataSize + " data elements:/n");
027:    for (int i = 0; i < dataSize; i++) {
028:     System.out.println("data[" + i + "] = " + data[i]);
029:    }
030:   } catch (EOFException eof) {         // Trap EOF exception
031:    System.err.println("File damaged or in wrong format");
032:   } catch (IOException e) {            // Trap exception
033:    System.err.println(e.toString());   // Display error
034:   }
035:  }
036: }
Return to top

Listing 24-9 WriteText/WriteText.java Page 578

Return to top
001: import java.io.*;
002: 
003: public class WriteText {
004: 
005:  static String[] text = {
006:   "This is a line of text",
007:   "This is the second line",
008:   "End of text" };
009: 
010:  // Main program method
011:  public static void main(String args[]) {
012:   try {
013:    // Create output file object
014:    BufferedWriter tout = 
015:     new BufferedWriter(new FileWriter("Data.txt"));
016:    for (int i = 0; i < text.length; i++) {
017:     tout.write(text[i]);
018:     tout.newLine();
019:    }
020:    tout.flush();
021:    tout.close();
022:    System.out.println("File created");
023:   } catch (IOException e) {            // Trap exception
024:    System.err.println(e.toString());   // Display error
025:   }
026:  }
027: }
Return to top

Listing 24-10 ReadRandom/ReadRandom.java Page 580

Return to top
001: import java.io.*;
002: 
003: public class ReadRandom {
004: 
005:  public static String readLine()
006:   throws IOException {
007:   BufferedReader br = 
008:    new BufferedReader(new InputStreamReader(System.in));
009:   return br.readLine();
010:  }
011: 
012:  // Prompt user for record number
013:  public static int getRecordNumber()
014:   throws IOException, NumberFormatException {
015:    System.out.print("Record number (-1 to quit)? ");
016:    return Integer.parseInt(readLine());
017:  }
018: 
019:  // Main program method
020:  public static void main(String args[]) {
021:   // Instance variables
022:   int dataSize;         // Number of elements in file
023:   int rn;               // Record number
024:   double value;         // Value of requested record
025:   int sizeOfInt = 4;    // Size of int variable
026:   int sizeOfDouble = 8; // Size of double variable  
027:   boolean wantsToQuit = false;
028:   try {
029:    // Create file objects
030:    File fi = new File("Data.bin");
031:    RandomAccessFile rin = new RandomAccessFile(fi, "r");
032:    dataSize = rin.readInt();     // Get number of elements
033:    // Prompt user for element to read
034:    System.out.println("/nFile has " + 
035:     dataSize + " elements/n");
036:    while (!wantsToQuit) {
037:     rn = getRecordNumber();
038:     wantsToQuit = (rn == -1);
039:     if (!wantsToQuit) {
040:      // Seek to requested record
041:      rin.seek(sizeOfInt + (rn * sizeOfDouble));
042:      // Read and display value
043:      value = rin.readDouble();
044:      System.out.println("Record " + rn + " = " + value);
045:     }
046:    }
047:   } catch (IOException e) {            // Trap exception
048:    System.err.println(e.toString());   // Display error
049:   }
050:  }
051: }
Return to top