File I/O Exercises

  < Previous  Next >

File Input

  1. Discuss with someone else the advantages and disadvantages of buffering.
  2. Given a Scanner object, how do know when we have read in the entire file contents?
  3. Given a BufferedReader object, how do know when we have read in the entire file contents?
  4. What does the following code do?
    do{
        line = reader.readLine();
        System.out.println( line );
    }while( line != null );
    For example, trace the execution for a file with 2 lines of contents. What about an empty file?
    How could the code be improved?
  5. What are the general steps for reading in the contents of a file?
  6. Write a complete Java program that displays each word from "javaOutput.txt" on a separate line. For example:
    Hello,
    world
  7. Extend the Java program to display the number of lines and characters (not including the line termination characters) in the file.

File Output

  1. What are the general steps for writing the contents to a file?
  2. What happens if you open a file that already exists and has contents?
  3. Write a complete Java program that writes "Hello, world" to a file named "javaOutput.txt"
  4. Write a complete Java program that prompts the user for a text input filename and an output filename. Assume that the input file contains only real numbers (for example, numbers.txt). For each of the values in the input file, multiple it by two and write it to the output file.