Java FileOutputStream Class
Java FileOutputStream is an output stream for writing data to a file.
If you had to write primitive values then use Fileoutputstream.instead, for character-oriented data, prefer FILEWRITER.BU T can write byte-oriented as well as character-oriented data.
Example of Java FileOutputStream class
- Import java.io.*;
- Class test{
- public static void Main (String args[]) {
- try{
- FileOutputStream fout=New FileOutputStream ("Abc.txt");
- String s="Sachin Tendulkar is my favourite player";
- byte b[]=s.getbytes (); //converting string into byte array
- Fout.write (b);
- Fout.close ();
- System.out.println ("Success ...");
- }catch (Exception e) {System.out.println (e);}
- }
- }
Output:success ...
Java FileInputStream Class
Java FileInputStream class obtains input bytes from a file. It is used for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
It should is used to read byte-oriented data for example to read image, audio, video etc.
Example of FileInputStream class
- Import java.io.*;
- Class simpleread{
- public static void Main (String args[]) {
- try{
- FileInputStream fin=New FileInputStream ("Abc.txt");
- int i=0;
- While ((I=fin.read ())!=-1) {
- System.out.println ((char) i);
- }
- Fin.close ();
- }catch (Exception e) {System.out.println (e);}
- }
- }
Output:sachin is my favourite player.
Example of Reading The data of current Java file and writing it into another file
We can read the data of any file using the FileInputStream class whether it is Java file, image file, video file etc. In this example, we is reading the data of C.java file and writing it into another file M.java.
- Import java.io.*;
- Class c{
- Public static void Main (String args[])throws exception{
- FileInputStream fin=New FileInputStream ("C.java");
- FileOutputStream fout=New FileOutputStream ("M.java");
- int i=0;
- while ((I=fin.read ())!=-1) {
- Fout.write ((byte) i);
- }
- Fin.close ();
- }
- }
FileInputStream and FileOutputStream