zoukankan      html  css  js  c++  java
  • FileInputStream and FileOutputStream

    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

    1. import java.io.*;  
    2. class Test{  
    3.   public static void main(String args[]){  
    4.    try{  
    5.      FileOutputstream fout=new FileOutputStream("abc.txt");  
    6.      String s="Sachin Tendulkar is my favourite player";  
    7.      byte b[]=s.getBytes();//converting string into byte array  
    8.      fout.write(b);  
    9.      fout.close();  
    10.      System.out.println("success...");  
    11.     }catch(Exception e){system.out.println(e);}  
    12.   }  
    13. }  
    Output:success...
    

    FileOutputStream example in I/O


    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

    1. import java.io.*;  
    2. class SimpleRead{  
    3.  public static void main(String args[]){  
    4.   try{  
    5.     FileInputStream fin=new FileInputStream("abc.txt");  
    6.     int i=0;  
    7.     while((i=fin.read())!=-1){  
    8.      System.out.println((char)i);  
    9.     }  
    10.     fin.close();  
    11.   }catch(Exception e){system.out.println(e);}  
    12.  }  
    13. }  
    Output:Sachin is my favourite player.
    

    Java FileInputStream


    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.

    1. import java.io.*;  
    2. class C{  
    3. public static void main(String args[])throws Exception{  
    4. FileInputStream fin=new FileInputStream("C.java");  
    5. FileOutputStream fout=new FileOutputStream("M.java");  
    6. int i=0;  
    7. while((i=fin.read())!=-1){  
    8. fout.write((byte)i);  
    9. }  
    10. fin.close();  
    11. }  
  • 相关阅读:
    AMR转换MP3 linuxCentOS 版(不管任何语言可以使用shell命令在linux执行转换语句)
    MySql 入门——日期计算
    javascript深度剖析之 【 var 关键字】。
    javascript动画浅析。
    javascript之this关键字浅析。
    javascript【AMD模块加载器】浅析V3(添加CSS加载功能,重构内部流程)
    html5 canvas 自制小游戏系列之 【贪吃蛇】。
    javascript设计模式简单介绍之【工厂模式】
    javascript【AMD模块加载器】浅析
    javascript【AMD模块加载器】浅析V2(整合DOM ready)
  • 原文地址:https://www.cnblogs.com/SummerinShire/p/5438027.html
Copyright © 2011-2022 走看看