android 5.0.2中的HttpURLConnection java.io.FileNotFoundException

时间:2015-03-28 11:53:46

标签: android httpurlconnection

我正在使用以下代码从服务器下载pdf文件并存储到SD卡中。它在Android 4.4设备上运行良好。虽然它不适用于Android 5.0.2设备。

public static String downloadFile(String fileUrl, File directory){
        try {

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(false);
            urlConnection.connect();


            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while((bufferLength = inputStream.read(buffer))>0 ){
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
            result = "true";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result = "false";
        } catch (MalformedURLException e) {
            e.printStackTrace();
            result = "false";
        } catch (IOException e) {
            e.printStackTrace();
            result = "false";
        }
        return result;
    }

在线:InputStream inputStream = urlConnection.getInputStream();我收到java.io.FileNotFoundException错误。

我尝试了很多东西,但没有奏效。帮我解决了这个错误。

0 个答案:

没有答案