在Android上以编程方式下载文件 [英] Download a file programmatically on Android
本文介绍了在Android上以编程方式下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在以编程方式从Web服务器下载文件.下载完成后,我检查了文件.大小,扩展名和所有其他参数都正确,但是当我尝试在媒体播放器中播放该文件时,表明文件已损坏.
I am downloading files from web server programmatically. After download is completed, I checked the file. The size ,extension and all other parameters are correct but when I try to play that file in media player it is showing that it is corrupted.
这是我的代码:
byte[] b = null;
InputStream in = null;
b = new byte[Integer.parseInt(size)]; // size of the file.
in = OpenHttpConnection(URL);
in.read(b);
in.close();
File folder = new File("/sdcard", "folder");
boolean check = folder.mkdirs();
Log.d("HttpDownload", "check " + check);
File myFile = new File("/sdcard/folder/" + name);
myFile.createNewFile();
OutputStream filoutputStream = new FileOutputStream(myFile);
filoutputStream.write(b);
filoutputStream.flush();
filoutputStream.close();
推荐答案
这是一些用于将给定URL下载到给定File对象的有效代码. File对象(outputFile)刚刚使用新的File(path)创建,我还没有称之为createNewFile或其他任何东西.
This is some working code I have for downloading a given URL to a given File object. The File object (outputFile) has just been created using new File(path), I haven't called createNewFile or anything.
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return; // swallow a 404
} catch (IOException e) {
return; // swallow a 404
}
}
这篇关于在Android上以编程方式下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文