go to previous page   go to home page   go to next page        

Answer:

Yes.

PrintStream

PrintStream is used for character output to a text file. Here is a program that creates the file myOutput.txt and writes several lines of characters to that file.

import java.io.*;

class PrintTextFile 
{

  public static void main ( String[] args ) throws IOException
  {
    File file = new File( "myOutput.txt" );
    PrintStream  print = new PrintStream( file );

    print.println( "The world is so full"  );  
    print.println( "Of a number of things,"  );  
    print.println( "I'm sure we should all" );  
    print.println( "Be as happy as kings."  );  

    print.close();
  }
}

The program first creates a File object that represents the disk file.

    File file = new File( "myOutput.txt" );

Next the program connects the file to an output PrintStream. If the file already exists its contents will be destroyed, unless the user does not have permission to alter the file. If this is the case, an IOException will be thrown and the program will end. (Most modern operating systems implement file permissions, where files can be marked read only.)

    PrintStream  print = new PrintStream( file );

Several lines of characters are sent to the output stream (and to the file). Each line ends with the control characters that separate lines:

    print.println( "The world is so full"  );  
    print.println( "Of a number of things,"  );  
    print.println( "I'm sure we should all" );  
    print.println( "Be as happy as kings."  );  

Finally, the stream is closed. This means that the disk file is completed and now is available for other programs to use.

    print.close();

The file would be closed when the program ended without using the close() method. But sometimes you want to close a file before your program ends.

QUESTION 12:

Could the TYPE command be used in the Windows command window (the DOS prompt window) to see the contents of this file?