gpt4 book ai didi

java - 性能: BufferedOutputStream vs FileOutputStream in Java

转载 作者:行者123 更新时间:2023-12-02 07:31:25 25 4
gpt4 key购买 nike

我读到 BufferedOutputStream 类可以提高效率,必须以这种方式与 FileOutputStream 一起使用 -

BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("myfile.txt"));

对于写入同一文件,下面的语句也有效 -

FileOutputStream fout = new FileOutputStream("myfile.txt");

但是推荐的方法是使用 Buffer 进行读/写操作,这就是我也更喜欢使用 Buffer 进行读/写操作的原因。

但我的问题是如何衡量上述两个语句的性能。他们有什么工具或某种东西吗,不知道到底是什么?但这对于分析其性能很有用。

作为JAVA语言的新手,我很好奇。

最佳答案

缓冲仅在您进行低效读取或写入时才有用。对于阅读而言,即使您可以使用 read(byte[]) 或 read(char[]) 更快地吞噬字节/字符,它也有助于让您逐行读取。对于写入,它允许您使用缓冲区缓冲要通过 I/O 发送的内容,并且仅在刷新时发送它们(请参阅 PrintWriter (PrintOutputStream(?).setAutoFlush())

但是如果您只是想尽可能快地读取或写入,缓冲并不能提高性能

有关高效读取文件的示例:

File f = ...;
FileInputStream in = new FileInputStream(f);
byte[] bytes = new byte[(int) f.length()]; // file.length needs to be less than 4 gigs :)
in.read(bytes); // this isn't guaranteed by the API but I've found it works in every situation I've tried

与低效阅读:

File f = ...;
BufferedReader in = new BufferedReader(f);
String line = null;
while ((line = in.readLine()) != null) {
// If every readline call was reading directly from the FS / Hard drive,
// it would slow things down tremendously. That's why having a buffer
//capture the file contents and effectively reading from the buffer is
//more efficient
}

关于java - 性能: BufferedOutputStream vs FileOutputStream in Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43528057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com