public class Doubler
1: //Doubler.java
2:
3: import java.io.FileInputStream;
4: import java.io.FileOutputStream;
5: import java.io.ObjectInputStream;
6: import java.io.ObjectOutputStream;
7: import java.io.EOFException;
8: import java.io.FileNotFoundException;
9: import java.io.IOException;
10: import java.util.Scanner;
11:
12: public class Doubler
13: {
14: private ObjectInputStream inputStream = null;
15: private ObjectOutputStream outputStream = null;
16:
17: /**
18: * Doubles the integers in one file and puts them in another file.
19: */
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("Numbers from input file");
28: System.out.println("doubled and copied to output file.");
29: }
30:
31: public void connectToInputFile()
32: {
33: String inputFileName = getFileName("Enter 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: }
50:
51: private String getFileName
52: (
53: String prompt
54: )
55: {
56: String fileName = null;
57: System.out.println(prompt);
58: Scanner keyboard = new Scanner(System.in);
59: fileName = keyboard.next();
60: return fileName;
61: }
62:
63: public void connectToOutputFile()
64: {
65: String outputFileName = getFileName("Enter name of output file:");
66: try
67: {
68: outputStream =
69: new ObjectOutputStream(new FileOutputStream(outputFileName));
70: }
71: catch (IOException e)
72: {
73: System.out.println("Error opening output file " + outputFileName);
74: System.out.println(e.getMessage());
75: System.exit(0);
76: }
77: }
78:
79: public void timesTwo()
80: {
81: try
82: {
83: while (true)
84: {
85: int next = inputStream.readInt();
86: outputStream.writeInt(2 * next);
87: }
88: }
89: catch (EOFException e)
90: {
91: //Do nothing. This just ends the loop.
92: }
93: catch (IOException e)
94: {
95: System.out.println("Error: reading or writing files.");
96: System.out.println(e.getMessage());
97: System.exit(0);
98: }
99: }
100:
101: public void closeFiles()
102: {
103: try
104: {
105: inputStream.close();
106: outputStream.close();
107: }
108: catch (IOException e)
109: {
110: System.out.println("Error closing files " + e.getMessage());
111: System.exit(0);
112: }
113: }
114: }