我在java中编写了一个小的html网络服务器。我刚刚实现了一个fileupload功能,但我遇到了一个问题。
浏览器通过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();
长度是后体的大小 - &gt;所以for循环知道它何时结束。这种方法非常有效 - 在Windows上。但不是在linux上!实际上字节流小于体长,所以我的脚本等待新的字节/数据包,直到达到后体长度。例如,最后的输出是:
229404.280212
237597.280212
245790.280212
253983.280212
的 262176 0.280212
号码&#34; 262176&#34;应该是280212.此时,我的服务器等待新的数据包......
感谢您的帮助。
答案 0 :(得分:1)
我认为这里存在一些问题以及一些误解。
为什么用++运算符递增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循环中添加一个超时,并且还要添加套接字超时,这样你就不会陷入无限循环,也不会在读取时遇到无限块。
另请注意,Java中的char长度为2个字节。
答案 1 :(得分:0)
最后,我解决了这个问题。使用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();
}