我正在通过网络服务提供的网址从服务器下载文件。 我对每个版本的设备都很成功,但在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;
}
}
我在 c.getInputStream(); 行获得java.io.FileNotFoundException 请建议我解决这个问题。
我打算使用内部存储器,但由于用户无法访问内部存储器。
答案 0 :(得分:6)
试试这段代码: 请注意,创建文件的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;
}
答案 1 :(得分:-2)
试试这段代码:
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
并添加清单:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />