【问题标题】:Android - file download problem - incomplete fileAndroid - 文件下载问题 - 文件不完整
【发布时间】:2011-02-03 10:29:14
【问题描述】:

我检查了许多代码 sn-ps,尝试了使用和不使用缓冲区,但我无法将整个文件下载到 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 字节的文件。可能是什么问题?

【问题讨论】:

  • 你怎么知道只下载了77byte?
  • @chirag-shag 77 bytes 是 DDMS Emulator SD 卡文件资源管理器中文件的大小
  • 预期的结果是什么?您是否尝试过使用 wget 或 curl 之类的工具下载相同的内容来与您的代码下载的内容进行比较?您创建的 77 字节文件的内容是什么?

标签: java android file download


【解决方案1】:

这里的错误是他正在编写转换为byte 数据类型的count 变量,而不是从输入流中读取的字节(那些应该通过bis.read(buffer) 存储在临时byte[] buffer 中) 正确的代码块应该是:

BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(file);
int current = 0;
byte[] buffer = new byte[1024];
while ((current = bis.read(buffer)) != -1) {
    fos.write(buffer, 0, current);
}
fos.close();
is.close();

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多