Java FileInputStream and FileOutputStream

The FileReader and FileWriter streams handle 16-bit Unicode characters, so would normally be used when handling files containing textual data. The equivalent byte streams, FileInputStream and FileOutputStream, handle ISO-Latin 8-bit bytes. Typically, these streams would be used for handling image and sound data. The ReadWriteFile example reads the contents of file File1.txt using FileInputStream and writes them to File2.txt using FileOutputStream.


ReadWriteFile

import java.io.*;

public class ReadWriteFile
{

public static void main(String[] args) throws
IOException
{
int c;

File inputFile = new File(''File1.txt");
File outputFile = new File("File2.txt");
FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream(outputFile);

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



In lines 9–10, we create file objects, inputFile and outputFile. In lines 11–13, we then use FileInputStream and FileOutputStream constructors to create the two stream objects, in and out. Line 14 uses the java.io.FileInputStream.read method in the same way as the java.io.FileReader.read method described in Section 7.2.5. Most of the methods in the

FileReader and FileWriter classes have an equivalent in FileInputStream and FileOutputStream, respectively.

No comments:

Post a Comment