android开发中,使用到了文件下载并写入到SD卡中,但是每次下载到的文件都不完整。

2025-01-05 09:18:25
推荐回答(4个)
回答1:

public File writeToSDFromInput(String path, String fileName,
InputStream inputStream) {
File file = null;
OutputStream outputStream = null;
createSDDir(path);
try {
file = createFileInSDCard(fileName, path);
outputStream = new FileOutputStream(file);
byte buffer[] = new byte[4 * 1024];
int temp;
while ((temp = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, temp);
}
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;

回答2:

file = createFileInSDCard(fileName, path);
outputStream = new FileOutputStream(file);
byte buffer[] = new byte[4 * 1024];
int temp;
while ((temp = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, temp);
}
outputStream.flush();
} catch (IOException e) {

回答3:

刚好遇到,我来回答,请给我点赞。

不谢。

        byte buffer [] = new byte[4 * 1024];  
//      while((input.read(buffer)) != -1){  
//          output.write(buffer);  
//      }  
          
        int length;   
        while((length=(input.read(buffer))) >0){   
        output.write(buffer,0,length);   
        }

回答4:

你解决了吗?我的代码跟你的基本一样,也是下载不完整