Thursday, September 11, 2008

read and write files

Using Streams to Read and Write Files

File streams are perhaps the easist streams to understand. Simply put, FileInputStream (FileOutputStream) represent an input (output) stream on a file that lives on the native file system. You can create a file stream from the filename, a File object or a FileDescriptor object. Use these streams to read data from or write data to files on the file system.

This small example uses the file streams to copy the contents of one file into another.

import java.io.*;

class FileStreamsTest {
public static void main(String args[]) {
try {
FileInputStream fis = new FileInputStream("farrago.txt");
FileOutputStream fos = new FileOutputStream("outagain.txt");
int c;

while ((c = fis.read()) != -1) {
fos.write(c);
}

fis.close();
fos.close();
} catch (FileNotFoundException e) {
System.err.println("FileStreamsTest: " + e);
} catch (IOException e) {
System.err.println("FileStreamsTest: " + e);
}
}






http://telecom.ntua.gr/HTML.Tutorials/java/io/streampairs.html#FILES



}

No comments: