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