我读到 BufferedOutputStream 类提高了效率,必须以这种方式与 FileOutputStream 一起使用 -
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("myfile.txt"));
Run Code Online (Sandbox Code Playgroud)
对于写入同一文件,下面的语句也适用 -
FileOutputStream fout = new FileOutputStream("myfile.txt");
Run Code Online (Sandbox Code Playgroud)
但推荐的方法是使用 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
Run Code Online (Sandbox Code Playgroud)
与低效阅读相比:
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
}
Run Code Online (Sandbox Code Playgroud)