What are the FileInputStream and FileOutputStream?

Solution:

Java FileOutputStream is an output stream used for writing data to a file. If you have some primitive values to write into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through the FileOutputStream class. However, for character-oriented data, it is preferred to use FileWriter than FileOutputStream. Consider the following example of writing a byte into a file.

import java.io.FileOutputStream;  
public class FileOutputStreamExample {  
    public static void main(String args[]){  
           try{  
             FileOutputStream fout=new FileOutputStream("D:\\testout.txt");  
             fout.write(65);  
             fout.close();  
             System.out.println("success...");  
            }catch(Exception e){System.out.println(e);}  
      }  
}  

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video, etc. You can also read character-stream data. However, for reading streams of characters, it is recommended to use FileReader class. Consider the following example for reading bytes from a file.

import java.io.FileInputStream;  
public class DataStreamExample {  
     public static void main(String args[]){  
          try{  
            FileInputStream fin=new FileInputStream("D:\\testout.txt");  
            int i=fin.read();  
            System.out.print((char)i);  
  
            fin.close();  
          }catch(Exception e){System.out.println(e);}  
         }  
        }  
  
0 answers