 |
|

|
 |

010/01/09 - Writing and Reading Files
|
 |
 |
 |
  | Generating random integers, opening a file for writing, writing to a file and closing the file
|
 |
 |
 |
 |
  | /** * Demo of random integer generation and * writing to a file. * * @author Chuck Iverson * @version 9/24/09 */
import java.util.*; import java.io.*;
public class TestRandom { public static void main(String [] args) throws IOException { PrintWriter writer = new PrintWriter("MyOutput.txt"); Random rand = new Random(); Scanner keyboard = new Scanner(System.in); int lower, upper; boolean valid; System.out.print("Enter lower bound: "); lower = keyboard.nextInt(); writer.println("Lower bound: " + lower); do { System.out.print("Enter upper bound (> " + lower + "): "); upper = keyboard.nextInt(); valid = upper > lower; if (!valid) System.out.println(upper + " is not > " + lower + ". Try again."); } while (!valid); writer.println("Upper bound: " + upper); int value; for (int i = 0; i < 10; ++i) { value = lower + rand.nextInt(upper-lower+1); System.out.println(value); writer.println(value); } writer.close(); } }
|
 |
 |
 |
 |
  | Opening a file for reading with a Scanner, reading a file as strings and closing the file
|
 |
 |
 |
 |
  | /** * Read information from a file * * @author Chuck Iverson * @version 9/24/09 */
import java.io.*; import java.util.Scanner;
public class ReadFile { public static void main(String [] args) throws IOException { File infile = new File("MyOutput.txt"); Scanner fileInput = new Scanner(infile); String s; while (fileInput.hasNextLine()) { s = fileInput.nextLine(); System.out.println(s); } fileInput.close(); } }
|
 |
 |
 |
 |
  | We can use all the standard Scanner methods to read from a file, just as we read from the keyboard:
|
 |
 |
 |
 |
  | fileInput.nextInt(), fileInput.nextDouble(), ...
|
 |
 |
 |
 |
  | However, you need to know the structure of the file to read it correctly. In other words, you need to know which lines are strings, which lines have integers, doubles, etc.
|
 |
 |
 |
 |
  | Write the code that would read the file data.txt (below) with the following content and write to an output file the strings, the sum of all the integer values and the average of all the double values.
|
 |
 |
 |
 |
  | Four-score and seven years ago... 5 8 13 22 A tisket a tasket 3.14 5.6 -234.87 92 a green and yellow basket -18 32 1.78 3.42 98.6
|
 |
 |
 |
 |
  | Write a program that prompts the user for a file name, then reads that file (assuming that its contents consist entirely of integers) and prints the input file name, the maximum, the minimum, the sum, the count (number of integers in the file), and the average of the numbers to the file output.txt. For example, if the file NumberInput.txt has the following contents:
4 -2 18 15 31
27
your program should create the file output.txt with the following content:
Input file name: NumberInput.txt Maximum: 31 Minimum: -2 Sum: 93 Count: 6 Average: 15.5
|
 |
 |
|


 |
 |
 |