Maximilian.
2021-08-13 18:34
采纳率: 50%
浏览 33
已结题

为什么Java的缓冲流在复制文本文档内容上消耗的时间比普通的输入输出流长呢?

同为复制这样的文本文件(如图)

img

编写的代码如下:


import java.io.*;
import java.util.Scanner;

/**
 * @author Maximilian_Li
 */
public class TestEfficiency {
    public static void main(String[] args) throws IOException {
        String basicFilePath = "D:\\Java\\Note&Code\\Java_Network_Programming\\src\\Chapter01_Stream\\" +
                "Section03_BufferedStream\\";

        String filePathFrom = basicFilePath + "from.txt";

        String filePathTo = basicFilePath + "to.txt";

        File fromFile = new File(filePathFrom);
        File toFile = new File(filePathTo);

        while(true) {
            Scanner sc = new Scanner(System.in);
            System.out.println("\r\n请输入你的选择(【1】代表普通输入输出流,【2】代表缓冲输入输出流)。\r\n");
            int anInt = sc.nextInt();

            switch (anInt) {
                case 1:
                    FileInputStream fromStream = new FileInputStream(fromFile);
                    FileOutputStream toStream = new FileOutputStream(toFile);

                    System.out.println("普通流所需时间  : " + timeOfOriginal(fromStream, toStream));

                    break;
                case 2:
                    BufferedReader buffFrom = new BufferedReader(new FileReader(fromFile));
                    BufferedWriter buffTo = new BufferedWriter(new FileWriter(toFile));

                    System.out.println("缓冲流所用时间  : " + timeOfBuffered(buffFrom, buffTo) + "\r\n");

                    break;
                default:
                    System.exit(0);
            }
        }
    }

    private static long timeOfBuffered(BufferedReader buffFrom, BufferedWriter buffTo) throws IOException {
        long startTime = System.currentTimeMillis();
        System.out.println(startTime);

        String aLine = null;
        while ((aLine = buffFrom.readLine()) != null) {
            buffTo.write(aLine);
            buffTo.newLine();
        }

        buffFrom.close();
        buffTo.close();

        long endTime = System.currentTimeMillis();
        System.out.println(endTime);

        return (endTime - startTime);
    }

    private static long timeOfOriginal(FileInputStream fromStream, FileOutputStream toStream) throws IOException {
        long startTime = System.currentTimeMillis();
        System.out.println(startTime);

        int length = 0;
        byte[] bytes = new byte[1024];

        while ((length = fromStream.read(bytes)) != -1) {
            toStream.write(bytes,0,length);
        }

        fromStream.close();
        toStream.close();

        long endTime = System.currentTimeMillis();
        System.out.println(endTime);

        return (endTime - startTime);
    }
}

输出结果为这样(如图)

img

但是据我了解,缓冲流的效率是远高于普通输入输出流的,为什么会出现这种状况呢?

2条回答 默认 最新

相关推荐 更多相似问题