Top
Previous Next
Java's Object Orientation, I/O CS 161 - Java

Simple File I/O - Readers / Writers

Source: examples/CopyChars.java



/** adapted from JavaTutorial: example of simple file I/O using
** classes derived from Reader and Writer.
**/
 
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
 
public class CopyChars {
 
public static void main(String[] args) {
if (args.length != 1)
System.out.println("usage: CopyChars file_to_copy");
else {
CopyChars obj = new CopyChars();
try {
obj.makeCopy(args[0]);
}
catch (IOException e) {
System.out.println(e);
}
}
}
 
public void makeCopy(String filename) throws IOException {
FileReader in = new FileReader(filename);
FileWriter out = new FileWriter(filename + ".copy");
 
int c;
 
// Read characters from the reader until in.read returns -1
while (true) {
c = in.read();
if (c == -1)
break;
out.write(c);
}
 
in.close();
out.close();
}
}


Top
Previous Next
jwd