Reading and writing in Java

Reading and writing from and to files is not easy in Java. This can already be seen if one simply googles on “Java Filereader problem”. This generated 477000 hits. Apparently, reading (and writing) is not trivial. I wrote a small program that is able to read a file and copy its contents to another file. It is tested on both Windows and Linux and it seems to work.

A minor note on using the programme on Windows. To circumvent problems with the backslash, it is preceded by another backslash. Hence the filename is written as “D:\\bla bla”, where one might expect a “D:\bla bla”. The cause is that a backslash is interpreted as an exception character. (and not as a directory seperator. Hence the necessity to use the double backslash “\\” instead of a single one. Then the EOF character. In Windows, this EOF character can be enforced by a “\r\n”, whereas such EOF character is “\n” when it comes down to Linux.

I use a buffered read to hadle buffers. This enables this programme to be used with large input files.

import java.io.*;
 
public class CopyCharacters {
    public static void main(String[] args) throws IOException {
 
    	BufferedReader bufferedReader = null;
        FileWriter outputStream = null;
        String filename = "D:\\Users\\tmaanen\\prive\\java\\invoer.txt";
 
        try {
            bufferedReader = new BufferedReader(new FileReader(filename));
            File file = new File("D:\\Users\\tmaanen\\prive\\java\\characteroutput.txt");
            file.createNewFile();
            outputStream = new FileWriter(file, true);    
            int c;
            while ((c = bufferedReader.read()) != -1) 
                 {
                    outputStream.write(c);
                  }
            }
            catch (Exception e)
            {
              System.err.format("Exception occurred trying to read '%s'.", filename);
              e.printStackTrace();
            }
         finally {
            if (bufferedReader != null) 
            {
            	bufferedReader.close();
            }
            if (outputStream != null) 
            {
            	outputStream.write("\r\n");
            	outputStream.close();
            }
                }
    }
}

Door tom