Java Tutorial: Example of Reading and Writing a File

Xah Lee, 2005-03-23, 2006-08-26

The following program is a example that makes a copy of file, by reading the file content char by char and writing it out.


import java.io.*;

public class rFile {
     public static void main(String[] args) throws IOException {
         File inputFile = new File("/Users/t/t.txt");
         File outputFile = new File("/Users/t/t2.txt");

         FileReader in = new FileReader(inputFile);
         FileWriter out = new FileWriter(outputFile);
         int c;

         while ((c = in.read()) != -1)
            out.write(c);

         in.close();
         out.close();
     }
}

Note: in order to read or write a file in Java, one needs not only create a input file object and output file object, but also a FileReader object to read it and FileWriter object to write to it.

References:

Note: This page was originally based on http://java.sun.com/docs/books/tutorial/essential/io/filestreams.html , accessed on 2005-03. Page Not Found as of 2006-08.


See also:


Page created: 2005-03.
© 2005 by Xah Lee.
Xah Signet