IO流的复制

一:字节流(还有缓冲字节流方式):

 1 public static void main(String[] args) throws Exception {
 2         // 1:输入流
 3         FileInputStream fis = new FileInputStream("1.png");
 4         // 2:输出流
 5         FileOutputStream fos = new FileOutputStream("1copy.png");
 6         // 实现复制
 7         byte[] buf = new byte[1024];
 8         int count=0;
 9         while ((count=fis.read(buf)) != -1){
10             System.out.println(count);
11             fos.write(buf,0,count);
12         }
13 
14         // 关闭流
15         fis.close();
16         fos.close();
17         System.out.println("处理完毕");
18 
19     }

二:字符流:

 1 public static void main(String[] args) throws Exception {
 2         FileReader fr = new FileReader("file.txt");
 3         FileWriter fw = new FileWriter("fileCopy.txt");
 4 
 5         //第一种:单个读取
 6 //        int data=0;
 7 //        while((data=fr.read()) != -1){
 8 //            fw.write(data);
 9 //            fw.flush();
10 //        }
11         // 第二种:放到缓冲区
12         char[] contents = new char[1024];
13         int data=0;
14         while ((data=fr.read(contents)) != -1){
15             fw.write(new String(contents,0,data));
16         }
17 
18         fr.close();
19         fw.close();
20         System.out.println("复制完成");
21     }

 

posted @ 2022-06-11 17:39  现在开始JAVA  阅读(32)  评论(0)    收藏  举报