Java从浏览器读取字节流不同的正文长度

Java read byte stream from browser different body lengths

本文关键字:正文 浏览器 读取 字节流 Java      更新时间:2023-09-26

我用java编写了一个小型html Web服务器。我刚刚实现了文件上传功能,但我遇到了问题。

浏览器通过XMLHttpRequest()发送文件,我的网络服务器读取文件的字节流,如下所述。

    char[] buffer = new char[1024 * 8];
    int n;
    int total = 0;
    for(int count = 0; count < length; count++){
        System.out.println(count + "." + length);
        n = input.read( buffer );
        fileWriter.write( buffer, 0, n );
        count += n;
        total = count;
    }
    fileWriter.close();

长度是后正文的大小 ->因此 for 循环知道何时结束。这种方法在窗户上完美运行。但不是在 Linux 上!事实上,字节流小于正文长度,所以我的脚本等待新的字节/数据包,直到达到后正文长度。例如,最后的输出是:

229404.280212
237597.280212
245790.280212
253983.280212
262176.280212

数字"262176"应280212。此时,我的服务器正在等待新数据包...

感谢您的帮助。

我认为这里有一些问题和一些误解。

为什么要使用 ++ 运算符递增count?它只能通过每轮读取添加n来递增。total变量只是计数的另一个名称,您只需使用它将其从for范围内导出即可?为什么不直接创建count出圈呢?此外,现在的循环永远不会打印最后一次递增的结果 n ,因为当count递增到 - 或高于 length 时,循环终止。这意味着强制循环终止的值不会被循环打印。如果这段代码完全符合您的意图,我会感到惊讶。

我会用 while 循环替换你的 for 循环。

    char[] buffer = new char[1024 * 8];
    int total = 0;
    while (total < length){
        int n = input.read( buffer );
        fileWriter.write( buffer, 0, n );
        total += n;
        System.out.println(total + "." + length);
    }
    fileWriter.close();

您还希望在 try-with-resources 构造中使用文件编写器,而不是显式使用 close()。

您还应该确保在 wile 循环中添加超时,并添加套接字超时,这样您就不会陷入无限循环或读取时无限块。

另请注意,char 在 Java 中的长度为 2 个字节。

最后,我解决了这个问题。使用FileWriter是不好的。但是,尽管如此,还是要感谢所有试图帮助我的人。

public void copy (InputStream in , File file, int length) throws IOException {
    FileOutputStream fos = new FileOutputStream(file);
    int cnt = 0;
    byte[] buffer = new byte[1024 * 8];
    while(cnt < length)
    { 
        int n = in.read(buffer);
        fos.write(buffer, 0, n);
        cnt += n;
    }
    fos.flush();
    fos.close();
}