Java Tutorial: Example of Reading and Writing a File

, , 2006-08

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


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 = != -1)


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.

Java Doc: File Java Doc: FileReader Java Tutorial: file

Note: This page was originally based on

blog comments powered by Disqus