我正在通过Web服务提供的URL从服务器下载文件.我对每个版本的设备都很成功,但在OS 4.1设备中却出现异常.我使用下面的代码:
public static Boolean DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我在第c.getInputStream()行获得java.io.FileNotFoundException ; 请建议我解决这个问题.
我打算使用内部存储器,但由于用户无法访问内部存储器.
试试这段代码:请注意,创建文件的CONTEXT可以是Activity/ApplicationContext/etc.
public boolean downloadFile(final String path)
{
try
{
URL url = new URL(path);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File file = new File(CONTEXT.getDir("filesdir", Context.MODE_PRIVATE) + "/yourfile.png");
if (file.exists())
{
file.delete();
}
file.createNewFile();
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10817 次 |
| 最近记录: |