Java FileOutputStream class
Java FileOutputStream is an output stream for writing data to a file.
If you have to write primitive values then use FileOutputStream.Instead, for character-oriented data, prefer FileWriter.But you 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 be 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 are 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();
- }
- }
时间: 2024-10-05 19:12:04