我用 java 编写了一个小型 html 网络服务器。我刚刚实现了文件上传功能,但遇到了问题。
浏览器通过 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 循环知道何时结束。此方法在 Windows 上完美运行。但在linux上不行!事实上,字节流小于主体长度,因此我的脚本等待新的字节/数据包,直到达到主体长度。例如,最后的输出是:
229404.280212
237597.280212
245790.280212
253983.280212
262176.280212
数字“262176”应该是280212。此时,我的服务器正在等待新数据包...
感谢您的帮助。
最佳答案
我认为这里存在一些问题,也存在一些误解。
为什么要使用++ 运算符来增加 count
?它只能通过在每轮读取中添加 n
来递增。
total
变量只是 count 的另一个名称,您只需使用它从 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 循环中添加超时,并添加套接字超时,这样您就不会陷入无限循环或读取时陷入无限 block 。
另请注意,Java 中的 char 长度为 2 个字节。
关于javascript - Java从浏览器读取不同body长度的字节流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36118276/