Character stream, byte stream -- copy file

From , 5 Years ago, written in Java, viewed 170 times.
URL https://pastebin.vip/view/5caf41d6
  1. package s1214字符流字节流;
  2. /*1.注意,字符流可以读取中文,但是字节流不能显示中文,因为1字符=2字节,1个汉字用2字节表示,英文都是1字节。而且字符流读取效率
  3.  * 更高,所以读取文本一般用字符流。
  4.  * 2.单是字符流只能复制文本文件,字节流可以复制歌曲,等等任何文件
  5.  */
  6.  
  7. import java.io.FileInputStream;
  8. import java.io.FileNotFoundException;
  9. import java.io.FileOutputStream;
  10. import java.io.FileReader;
  11. import java.io.IOException;
  12.  
  13.  
  14. //字符流和字节流复制文本********************************************************************************
  15. public class Main
  16. {       public static void main(String[] args) throws IOException   //一定要加上throws IOException语句
  17.         {
  18.             copyProgram();
  19.         copyText();
  20.         }
  21.  
  22. public static void copyProgram() throws IOException {
  23.         //被复制的文件,用FileInputStream
  24.     FileInputStream input=new FileInputStream("C:/Users/Administrator/Desktop/歌/Just One Last Dance.mp3");
  25.     //复制后的文件,用FileOutputStream
  26.     FileOutputStream output=new FileOutputStream("C:/Users/Administrator/Desktop/歌/new/Just One Last Dance.mp3");
  27.     int aa; //读取一个字符 必须定义为整形
  28.     aa=input.read();
  29.  
  30.     while(aa!=(-1))                 //aa接受的是啊茨克码,只有当什么都没有的情况下,aa才返回-1
  31.     {  output.write(aa);          
  32.        aa=input.read();
  33.     }
  34.  
  35.     output.flush();                     //FileOutputStream先flush一下,将流中的残留内容全部输入或者输出
  36.    input.close();                       //必须写关闭
  37.    output.close();                      //必须写关闭    
  38.    System.out.println("复制完毕");
  39. }
  40.  
  41. public static void copyText() throws FileNotFoundException, IOException {
  42.         FileReader s=new FileReader("C:/Users/Administrator/workspace/学习历程2015/src/s0123文件夹创建/Main.java");   //字符流,文本编码方式为ANSI就能显示中文,其他编码方式不能显示中文         //字符流
  43. //        FileInputStream s=new FileInputStream("C:/Users/Administrator/Desktop/早晨从中午开始.txt");//字节流
  44.         int aa; //读取一个字符 必须定义为整形
  45.         aa=s.read();
  46.         System.out.println("文件内容为:");
  47.      
  48.         while(aa!=(-1))                   //aa接受的是啊茨克码,只有当什么都没有的情况下,aa才返回-1
  49.           {  System.out.print((char)aa);  //这里要把aa强制转型为char类型输出
  50.              aa=s.read();
  51.           }      
  52.       s.close();                       //必须写关闭  
  53.   }
  54. }
  55.  

Reply to "Character stream, byte stream -- copy file"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website