1 import java.io.File;
 2 import java.io.FileNotFoundException;
 3 import java.io.FileReader;
 4 import java.io.FileWriter;
 5 import java.io.IOException;
 6 
 7 /* This is a much more complicated example!  You are NOT expected to understand
 8    everything about how this works. It is simply meant to illustrate a means of
 9    performing input and output where the programmer has a bit more control. */
10 
11 public class FileIO_Byte {
12 
13     // NOTE: This is a slightly "lower level" means of performing file I/O. However,
14     //       it still assumes that "Charaters" are being manipulated. If you wish
15     //       to manipulate raw Bytes, you must use "InputStream" and "OutputStream".
16     public static void main(String[] args) {
17         File inFile = new File("C:/temp/infile.txt");
18         File outFile = new File("C:/temp/outfile.txt");
19         FileReader reader = null;
20         FileWriter writer = null;
21 
22         try {
23             reader = new FileReader(inFile);
24             writer = new FileWriter(outFile);
25 
26             // Priming read
27             int input = reader.read();
28 
29             // Read the rest
30             while (input != -1) {
31                 writer.write(input);
32                 input = reader.read();  // reads one character at a time (as an int).
33             }
34 
35             // How could we get rid of the priming read???
36 
37         } catch (FileNotFoundException ex) {
38             // If the file was not found, produce a message.
39             System.err.println("The File could not be found: " + ex.getMessage());
40         } catch (IOException ex) {
41             // A non file existence error has occurred.
42             System.err.println("Error: " + ex.getMessage());
43         } finally { // This will be done regadless of what happens above!
44             try {
45                 if (reader != null) {
46                     reader.close();
47                 }
48                 if (writer != null) {
49                     writer.close();
50                 }
51             } catch (IOException ex) {
52                 System.err.println("OOPS!... Could not even close the files!!!");
53             }
54         }
55 
56     }
57 }