0

我有以下代码,但我不确定我是否在效率/刷新/关闭流方面做得正确。一些建议会很有帮助,谢谢

    OutputStream out = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream(file, true));
        byte[] buf = new byte[32 * 1024]; // should this be 32KB?
        while ((in.read(buf)) > 0) {
            out.write(buf);
        }
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null)
                out.close();
            if (in != null)
                in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
4

2 回答 2

2

您遇到的最重要的问题是您忽略了读取的字节数。

for(int len; (len = in.read(buf)) > 0;) 
        out.write(buf, 0, len);

如果您不使用您假设的长度,您将始终准确读取 32 KB,这是一个很大的假设。


当您有很多小写时,缓冲区很有用。

BufferedOutputStream 的默认缓冲大小为 8 KB,如果您的写入比这小得多,即 < 512 字节,它们真的很有帮助。

但是,如果你写的是 32 KB,他们可能什么都不做,或者没有帮助。我会把它们拿出来。

顺便说一句,没有缓冲区,您不需要调用 flush();

顺便说一句

KB = 1024 bytes
kB = 1000 bytes
Kb = 1024 bits
kb = 1000 bits.
于 2015-08-25T16:08:24.910 回答
1

从“它是否有效”的角度来看,您的代码似乎还可以……但是,您可以通过使用资源尝试使看起来“更漂亮”。 尝试使用资源 您提供的代码基本上会变成以下内容:

try(OutputStream out = new BufferedOutputStream(new FileOutputStream(file, true)) {
    byte[] buf = new byte[1024];
    while ((in.read(buf)) > 0) {
        out.write(buf);
    }
    out.flush();
}

这是 Java7 的一个特性,如果流资源实现了 java.lang.AutoCloseable 那么它会自动关闭。

根据您尝试做的事情,以下内容可能是一个更简单的解决方案?

PrintStream p = new PrintStream(new BufferedOutputStream(new FileOutputStream(aFile, true)));
于 2015-08-25T16:19:27.960 回答