下载文件

通过URL,下载文件,并且保存在SD卡上

首先通过URL获得数据流

public InputStream getInputStreamFromUrl(String strUrl) {

InputStream input = null;

try {
URL url = new URL(strUrl);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
input = urlCon.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}

return input;
}


将数据流保存成文件

public File saveFileFromInput(String fileName, InputStream input) {

File file = null;
OutputStream output = null;

try {
createDir(mSDPath);
file = createFile(fileName);

output = new FileOutputStream(file);
byte buffer[] = new byte[4 * 1024];
while (input.read(buffer) != -1) {
output.write(buffer);
}

output.flush();

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return file;
}


([b][color=red]重要[/color][/b])如果无法保存,请查看是否添加必要Permission


你可能感兴趣的:(Java,Web,Android,Android)