【问题标题】:BufferOutputStream write zero byte when merge the file合并文件时BufferOutputStream写入零字节
【发布时间】:2012-07-13 03:35:30
【问题描述】:

我正在尝试将 n 个文件合并为单个文件。但是我的功能出现了奇怪的行为。该函数在 n 秒内被调用 x 次。假设我有 100 个文件要合并,每秒我调用 5 个文件并合并它。在下一秒,数量翻倍为 10,但从 1-5 是与之前相同的文件,其余的是新文件。它工作正常,但在某些时候,它给出零字节或有时给出正确的大小。

您能帮我找出下面函数中的错误吗?

public void mergeFile(list<String> fileList, int x) {
    int count = 0;
    BufferedOutputStream out = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream("Test.doc"));
        for (String file : fileList) {
            InputStream in = new BufferedInputStream(new FileInputStream(file));
            byte[] buff = new byte[1024];
            in.read(buff);
            out.write(buff);
            in.close();
            count++;
            if (count == x) {
                break;
            }
        }
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

*对不起我的英语

【问题讨论】:

  • mergeFile 是从线程中调用的吗?
  • 如果您尝试合并 MS Word doc 文件:我认为这不起作用,因为格式不允许。

标签: java io fileinputstream bufferedinputstream bufferedoutputstream


【解决方案1】:

您没有读取完整文件,您从每个文件中读取的内容最多 1024 个字节。只要读取返回数据,您就需要循环读取(或使用Files.copy()之类的东西。

顺便说一句:如果使用大缓冲区进行复制,则不需要 BufferedOutputStream。

public void mergeFile(list<String> fileList, int x) throws IOException {
    try (OutputStream out = new FileOutputStream("Test.doc");) {
        int count=0;
        for (String file : fileList) {
            Files.copy(new File(file).toPath(), out);
            count++;
            if (count == x) {
                break;
            }
        }
    }
}

如果你关闭,你也不需要flush()。我在这里使用“try-with-resource”,所以我不需要明确地关闭它。最好传播异常。

【讨论】:

    【解决方案2】:

    in.read(buff);

    检查Javadoc。该方法不能保证填充缓冲区。它返回一个值,告诉您它读取了多少字节。你应该使用那个,在这种情况下你应该在决定要写入多少字节(如果有的话)时使用它。

    【讨论】:

    • 对不起,我不明白你。你能解释一下吗?谢谢
    • @david 我添加了一个链接,如果您阅读它,请注意返回值。它可以是 0 到 1024(或 -1)之间的任何值。你必须循环直到它是-1。
    猜你喜欢
    • 2022-11-02
    • 2021-09-04
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    相关资源
    最近更新 更多