关于文件的复制(用InputStream和OutputStream)

时间:2021-05-19 03:13:01

作业:将c盘的一个文本文件复制到d盘。

分析:复制原理:读取c盘文件中的数据,将这些数据写入到d盘当中,连读带写。

/*

* 需求:作业:将c盘的一个文本文件复制到d盘。

* 思路:

* 1,需要读取源,

* 2,将读到的源数据写入到目的地。

* 3,既然是操作文本数据,使用字符流。

*/

第一种方式:

 public class CopyTextTest {
     public static void main(String[] args) throws IOException {
         //1,读取一个已有的文本文件,使用字符读取流和文件相关联。
         FileReader fr = new FileReader("IO流_2.txt");
         //2,创建一个目的,用于存储读到数据。
         FileWriter fw = new FileWriter("copytext_1.txt");
         //3,频繁的读写操作。
         int ch = 0;
         while((ch=fr.read())!=-1){
             fw.write(ch);
         }
         //4,关闭流资源。
         fw.close();
         fr.close();
     }
 }

第二种方式:(循环次数少,效率高。)

 public class CopyTextTest_2 {
     private static final int BUFFER_SIZE = 1024;
     public static void main(String[] args) {
         FileReader fr = null;
         FileWriter fw = null;
         try {
             fr = new FileReader("IO流_2.txt");
             fw = new FileWriter("copytest_2.txt");
             //创建一个临时容器,用于缓存读取到的字符。
             char[] buf = new char[BUFFER_SIZE];//这就是缓冲区。
             //定义一个变量记录读取到的字符数,(其实就是往数组里装的字符个数)
             int len = 0;
             while((len=fr.read(buf))!=-1){
                 fw.write(buf, 0, len);
             }
         } catch (Exception e) {
 //            System.out.println("读写失败");
             throw new RuntimeException("读写失败");
         }finally{
             if(fw!=null)
                 try {
                     fw.close();
                 } catch (IOException e) {

                     e.printStackTrace();
                 }
             if(fr!=null)
                 try {
                     fr.close();
                 } catch (IOException e) {

                     e.printStackTrace();
                 }
         }
     }
 }

原理图:

关于文件的复制(用InputStream和OutputStream)

有缓冲区可以提高效率。

java中把缓冲区封装了。

缓冲区的出现提高了文件的读写效率。

关闭缓冲区就是关闭的被缓冲的流对象!

所以只需要关闭缓冲区就可以,不必要再关闭流了。

复制文件用缓冲区的方式.

 public class CopyTextByBufTest {
     public static void main(String[] args) throws IOException {
         FileReader fr = new FileReader("buf.txt");
         BufferedReader bufr = new BufferedReader(fr);

         FileWriter fw = new FileWriter("buf_copy.txt");
         BufferedWriter bufw = new BufferedWriter(fw);

         String line = null;
         while((line=bufr.readLine())!=null){
             bufw.write(line);
             bufw.newLine();
             bufw.flush();
         }
         /*
         int ch = 0;
         while((ch=bufr.read())!=-1){
             bufw.write(ch);
         }
         */
         bufw.close();
         bufr.close();
     }
 }