Java 使用BufferInputStream下载时工作不正常
以下代码无法下载文件(顺便说一句,clen是文件的长度): …但这很好:Java 使用BufferInputStream下载时工作不正常,java,io,download,bufferedinputstream,Java,Io,Download,Bufferedinputstream,以下代码无法下载文件(顺便说一句,clen是文件的长度): …但这很好: int buf; while ((buf = in.read()) != -1) out.write(buf); 我想知道为什么,尽管第二个代码段工作得很快。在这一点上,使用byte[]缓冲区有什么特别的原因吗(因为它似乎没有更快,而且BufferedInputStream已经使用了自己的缓冲区……?)下面是应该如何做的 public static void copyStream(Inpu
int buf;
while ((buf = in.read()) != -1)
out.write(buf);
我想知道为什么,尽管第二个代码段工作得很快。在这一点上,使用byte[]缓冲区有什么特别的原因吗(因为它似乎没有更快,而且BufferedInputStream已经使用了自己的缓冲区……?)下面是应该如何做的
public static void copyStream(InputStream is, OutputStream os)
{
byte[] buff = new byte[4096];
int count;
try {
while((count = is.read(buff)) > 0)
os.write(buff, 0, count);
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(os != null)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我已尝试对代码进行必要的最小更改,以使其正常工作。st0le在提供更整洁的流复制版本方面做得很好
public class Test {
private static final String FORMAT = "UTF-8";
private static final int BUFFER_SIZE = 10; // for demonstration purposes.
public static void main(String[] args) throws Exception {
String string = "This is a test of the public broadcast system";
int clen = string.length();
ByteArrayInputStream in = new ByteArrayInputStream(string.getBytes(FORMAT));
OutputStream out = System.out;
int pos = 0, total_pos = 0;
byte[] buffer = new byte[BUFFER_SIZE];
while (pos != -1) {
pos = in.read(buffer, 0, BUFFER_SIZE);
if (pos > 0) {
total_pos += pos;
out.write(buffer, 0, pos);
setProgress((int) (total_pos * 100 / clen));
}
}
}
private static void setProgress(int i) {
}
}
- 将缓冲区写入输出流时,忽略了pos的值
- 您还需要重新检查pos的值,因为它可能刚刚读取了文件的末尾。在这种情况下,您不会增加总位置(尽管您可能应该报告您已经100%完成)
- 请确保在适当的位置使用close()正确处理资源
使用缓冲输入/输出流时使用它的好处可能很小。
而((pos=in.read(buffer))>0)
做得更干净。同意,但问题集中在为什么他的代码不起作用。所以我的首要任务是修复他的代码的错误。在这种情况下,我们有什么责任提供重新考虑的建议?我会考虑回答以后的问题。谢谢你st0le(和皮马斯特)。我发现我的错误在out中。写(缓冲区)
;这是在写入所有的缓冲区字节,而不是每次读取缓冲区时只写入那些字节。问题解决了!谢谢;)
public class Test {
private static final String FORMAT = "UTF-8";
private static final int BUFFER_SIZE = 10; // for demonstration purposes.
public static void main(String[] args) throws Exception {
String string = "This is a test of the public broadcast system";
int clen = string.length();
ByteArrayInputStream in = new ByteArrayInputStream(string.getBytes(FORMAT));
OutputStream out = System.out;
int pos = 0, total_pos = 0;
byte[] buffer = new byte[BUFFER_SIZE];
while (pos != -1) {
pos = in.read(buffer, 0, BUFFER_SIZE);
if (pos > 0) {
total_pos += pos;
out.write(buffer, 0, pos);
setProgress((int) (total_pos * 100 / clen));
}
}
}
private static void setProgress(int i) {
}
}