1

我正在借助通过 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;
                }
        }

我在c.getInputStream();行收到 java.io.FileNotFoundException 请建议我解决这个问题。

我打算使用内部存储器,但由于用户无法访问内部存储器。

4

2 回答 2

7

试试这个代码:请注意,创建文件的上下文可能是 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;
}
于 2012-09-25T16:30:03.980 回答
-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" /> 
于 2012-09-25T14:45:20.797 回答