2011-02-03 53 views
0

我检查了很多代码片段,尝试使用和不使用缓冲区,我无法将整个文件下载到SD卡。我现在使用的代码是:Android - 文件下载问题 - 文件不完整

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

你怎么能知道只有77byte被下载? – 2011-02-03 11:04:18

回答

1

这里的误差是他在写count变量转换为byte数据类型,而不是从输入流(那些应通过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();