Chapter 19
Input and Output

   19.1 Dialog Boxes
   19.2 Standard Output
   19.3 Standard Input
   19.4 Writing into Files
   19.5 Reading from Files
   19.6 Assignment #24: I/O
   19.7 Assignment #25: I/O + arrays

19.1 Dialog Boxes

19.2 Standard Output

System.out.println("The class of " + System.out + 
       " is " + (System.out).getClass().getName()); 
// The class of java.io.PrintStream@bf786fde is java.io.PrintStream 

19.3 Standard Input

class prg { 
  public static void main(String args[]) 
                 throws java.io.IOException { 
     int c; 
    c = System.in.read(); 
    System.out.print( c + " : " + (char)c ); 
    c = System.in.read(); 
    System.out.print( c + " : " + (char)c ); 
} } 

19.4 Writing into Files

try{ 
    FileWriter file = new FileWriter( "try.txt" ); 
    PrintWriter myout = new PrintWriter( file ); 
    myout.println("Hello, file!"); 
    myout.close(); 
} catch(java.io.IOException e){ 
    // do something 
} 

java.io: FileWriter, PrintWriter

19.5 Reading from Files

try{ 
   int c; 
   FileReader myIn  = new FileReader( "try.txt" ); 
   while( (c=myIn.read()) != -1 ){ 
     System.out.print( (char) c ); 
   } 
   System.out.println(); 
} catch(java.io.IOException e){ 
   // do something 
} 
try{ 
   String s; 
   FileReader fr  = new FileReader( "try.txt" ); 
   BufferedReader myIn = new BufferedReader( fr ); 
   while( (s=myIn.readLine()) != null ){ 
     System.out.println( s ); 
   } 
} catch(java.io.IOException e){ 
   // do something 
} 

java.io: FileReader, BufferedReader

19.6 Assignment #24: I/O

Tentative assignment; subject to change

Write a program that does the following.

  1. Prompts the user for an input file name through a dialog box.
  2. Prompts the user for an output file name through a dialog box.
  3. Copies the input file into the output file, subject to the removal of the space characters listed below from each line.
    1. The leading space characters
    2. The trailing space characters
    3. The space characters that are preceded by space characters
Example. An input
This is    a 
 fragment of 
         text. 
should result in the following output.
This is a 
fragment of 
text. 
Note: Files that fail to compile, and execute when applicable, will not be examined. They will be awarded a grade of 0 points.

Q&A

Assume ‘lab24’ for the submit program.

19.7 Assignment #25: I/O + arrays

Tentative assignment; subject to change

Write a program that reads 50 integer values from a file and prints out the following information

  1. The list of input values
  2. The list of input values in reverse order
  3. The largest value in the input
  4. The smallest value in the input
  5. A message stating whether the list of input values is equal to the list of input values in reverse order.
Assume ‘lab25’ for the submit program.

Q&A