Friday, July 19, 2013

FileInputStream vs. FileOutputStream

FileInputStream is a reading stream class in java.io package. It is used to connect to and read data from a binary file stored in a local disk. A binary file stores a collection of data. These data can be integers, characters, arrays, and other data structures. The binary file contains data that are meaningful only if they are properly interpreted by a program.

FileInputStream constructors:

-FileInputStream(String filename)
-FileInputStream(File file)

Its useful methods:

-read():int
-read(byte[] buffer):void

In this example, the content of the source file is read and output to the screen. The read method of the FileInputStream class reads one byte from the file at a time. You need to use a loop to read all bytes from the file. When the end of the file is reached, the read method return -1. So this value can be used to stop the loop process.

import java.io.*;
class ReadImage{
public static void main(String[] args){
try{
FileInputStream fs=new FileInputStream("image02.jpg"); //create inputstream to read data
int imgByte;
while((imgByte=fs.read())!=-1){ //read data
System.out.println(imgByte);
}

fs.close();
}catch(IOException ie){System.out.println("Error in reading the file…");}
}
}

FileOutputStream is a writing stream class that can be used to write data to a binary file. Its useful constructors and methods are shown below.

FileOutputStream Constructors:
-FileOutputStream(String filename)
-FileOutputStream(File file)
-FileOutputStream(String filename, boolean append)
-FileOutputStream(File file, boolean append)

Its ueful methods:
-write(byte b):void
-write(byte[] barray):void

In the example below, all bytes of the source file is read by using the read(byte[] buffer) method of the FileInputStream object. I you want to read only one byte one character from the file, you will use the read method instead. The content of the file are placed in the byte array called imgData. Then this array is written to the destination file by using the write(byte[] buffer) method of the FileOutputStream class.

import java.io.*;
class ImageCopy{
public static void main(String[] args){
try{

copyImage(args[0],args[1]);

}catch(ArrayIndexOutOfBoundsException aiob){
System.out.println("Invalid parameters input…");
}
}

public static void copyImage(String src, String desc) {
try{
File f=new File(src); //create file object
FileInputStream fs=new FileInputStream(f);//create input stream to read data

FileOutputStream fos=new FileOutputStream(desc);//create output stream to write data
byte[] imgData=new byte[(int)f.length()]; //create byte array to store data


fs.read(imgData); //read data
fos.write(imgData); //write data to the file
fos.flush(); //clear data from memory
fs.close(); //close data reader
fos.close();//close data writer

}catch(IOException ie){System.out.println("Error…" );}

}


}

No comments:

Post a Comment