java - inputstream流读到最后为什么没有返回 -1 ?
ringa_lee
ringa_lee 2017-04-18 10:52:57
0
1
929
InputStream fileSource = req.getInputStream();
String tempFile = "/home/joy/桌面/tempFile";
FileOutputStream tempFileOutputStream = new FileOutputStream(tempFile);
byte[] bytes = new byte[10 * 1024];
int i = 0;
while ((i = fileSource.read(bytes, 0, bytes.length)) != -1) {
    System.out.println("已读字节:" + i + ", 剩余字节: " + fileSource.available());
    System.out.println(new String(bytes));
    tempFileOutputStream.write(bytes);
    tempFileOutputStream.flush();
    if (fileSource.available() < bytes.length) {
        bytes = new byte[fileSource.available()];
    }
}
tempFileOutputStream.close();
fileSource.close();

为什么该流读完的时候并没有返回-1,而是返回0,导致无限循环.(上传文档类型文件不会,字节文件就会发生这种情况)

ringa_lee
ringa_lee

ringa_lee

Antworte allen(1)
黄舟

应该是你最后对buffer的处理导致刚刚好读取完文件吧

if (fileSource.available() < bytes.length) {
      bytes = new byte[fileSource.available()];
}

一般情况下不需要重设buffer的大小

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!