FileInputStream and FileOutputStream in java
In the previous post, We have seen FileReader which is used to read the data from text file. In this post, we will look at FileInputStream and FileOutputStream in java. These classes are used to read and write the data to a file i.e. used for file handling.
Let’s look at them with example.
FileOutputStream:
It is used to write the data as a stream of bytes into a file. The FileOutputStream class is a subclass of OutputStream meaning you can use a FileOutputStream as an OutputStream.
For writing character oriented data, we can use FileWriter.
Example of FileOutputStream:
public class FileHandlingEx { public static void main(String[] args){ try{ FileOutputStream fout=new FileOutputStream("Sample.txt"); String s="I am making a painting."; byte b[]=s.getBytes();//converting string into byte array fout.write(b); fout.close(); System.out.println("Write tasks successful."); }catch(Exception e){ System.out.println(e); } } }
FileInputStream:
It reads the content of File as a stream of bytes. It is a subclass of InputStream. For reading the stream of characters, we use FileReader class.
It can be used to read byte-oriented data for example to read image, audio, video etc.
Example of FileInputStream:
public class FileHandlingEx { public static void main(String[] args){ try{ FileInputStream fin=new FileInputStream("Sample.txt"); int i=0; while((i=fin.read())!=-1){ System.out.println((char)i); } fin.close(); }catch(Exception e){ System.out.println(e); } } }
1 Response
[…] the previous post, we have seen FileInputStream and FileOutputStream. In this post, we will look at BufferedInputStream and BufferedOutputStream in […]