我检查了很多代码片段,尝试使用和不使用缓冲区,我无法将整个文件下载到SD卡。我目前使用的代码是:
try {
url = new URL("http://mywebsite.com/directory/");
} catch (MalformedURLException e1) { }
String filename = "someKindOfFile.jpg"; // this won't be .jpg in future
File folder = new File(PATH); // TODO: add checking if folder exist
if (folder.mkdir()) Log.i("MKDIR", "Folder created");
else Log.i("MKDIR", "Folder not created");
File file = new File(folder, filename);
try {
conn = url.openConnection();
is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
is.close();
} catch (IOException e) { }
此代码在SD卡上创建目录,但仅下载77个字节的文件。可能是什么问题?
答案 0 :(得分:1)
这里的错误是他正在编写转换为count
数据类型的byte
变量,而不是从输入流中读取的字节(这些应存储在临时byte[] buffer
中{ {1}})
正确的代码块应该是:
bis.read(buffer)