public class Doubler
1: //Doubler.java
3: import java.io.FileInputStream;
4: import java.io.FileOutputStream;
5: import java.io.ObjectInputStream;
6: import java.io.ObjectOutputStream;
7: import java.io.FileNotFoundException;
8: import java.io.EOFException;
9: import java.io.IOException;
10: import java.util.Scanner;
12: /**
13: Doubles the integers in one file and puts them in another file.
14: */
15: public class Doubler
16: {
17: private ObjectInputStream inputStream = null;
18: private ObjectOutputStream outputStream = null;
20: public static void main(String[] args)
21: {
22: Doubler twoTimer = new Doubler();
23: twoTimer.connectToInputFile();
24: twoTimer.connectToOutputFile();
25: twoTimer.timesTwo();
26: twoTimer.closeFiles();
27: System.out.println("\nAll numbers from the input file have been");
28: System.out.println("doubled and copied to the output file.");
29: }
31: public void connectToInputFile()
32: {
33: String inputFileName = getFileName("\nEnter name of input file: ");
34: try
35: {
36: inputStream =
37: new ObjectInputStream(new FileInputStream(inputFileName));
38: }
39: catch(FileNotFoundException e)
40: {
41: System.out.println("File " + inputFileName + " not found.");
42: System.exit(0);
43: }
44: catch(IOException e)
45: {
46: System.out.println("Error opening input file " + inputFileName);
47: System.exit(0);
48: }
49: }
51: private String getFileName(String prompt)
52: {
53: String fileName = null;
54: System.out.print(prompt);
55: Scanner keyboard = new Scanner(System.in);
56: fileName = keyboard.next();
57: return fileName;
58: }
60: public void connectToOutputFile()
61: {
62: String outputFileName = getFileName("Enter name of output file: ");
63: try
64: {
65: outputStream =
66: new ObjectOutputStream(new FileOutputStream(outputFileName));
67: }
68: catch(IOException e)
69: {
70: System.out.println("Error opening output file " + outputFileName);
71: System.out.println(e.getMessage());
72: System.exit(0);
73: }
74: }
76: public void timesTwo()
77: {
78: try
79: {
80: while (true)
81: {
82: int next = inputStream.readInt();
83: outputStream.writeInt(2 * next);
84: }
85: }
86: catch(EOFException e)
87: {
88: //Do nothing. This just ends the loop.
89: }
90: catch(IOException e)
91: {
92: System.out.println("Error: reading or writing files.");
93: System.out.println(e.getMessage());
94: System.exit(0);
95: }
96: }
98: public void closeFiles()
99: {
100: try
101: {
102: inputStream.close();
103: outputStream.close();
104: }
105: catch(IOException e)
106: {
107: System.out.println("Error closing files " + e.getMessage());
108: System.exit(0);
109: }
110: }
111: }