-2

我从服务器下载 PDF 文件并将其保存在 SD 上时出现错误我有权访问互联网和外部存储.. 它在 android 2.3.6 上工作正常但在选项卡 4.1.1 上它创建的文件为 0 字节

URL url = new URL("https://docs.google.com/"+direct);
            //create the new connection
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            //set up some things on the connection
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setRequestProperty("Content-Type", "application/xml");
            urlConnection.setDoOutput(true);

            //and connect!
            urlConnection.connect();

            //set the path where we want to save the file
            //in this case, going to save it on the root directory of the
            //sd card.
            File SDCardRoot = new File(Environment.getExternalStorageDirectory().getAbsoluteFile()+"/folder/");
            //create a new file, specifying the path, and the filename
            //which we want to save the file as.
            File file = new File(SDCardRoot,book.getBook_name()+".pdf");

            //this will be used to write the downloaded data into the file we created
            FileOutputStream fileOutput = new FileOutputStream(file);

            //this will be used in reading the data from the internet
            InputStream inputStream = urlConnection.getInputStream();

            //this is the total size of the file
             totalSize = urlConnection.getContentLength();
            //variable to store total downloaded bytes

            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0; //used to store a temporary size of the buffer

            //now, read through the input buffer and write the contents to the file
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                    //add the data in the buffer to the file in the file output stream (the file on the sd card
                    fileOutput.write(buffer, 0, bufferLength);
                    //add up the size so we know how much is downloaded
                    downloadedSize += bufferLength;
                    //this is where you would do something to report the prgress, like this maybe
                    publishProgress((downloadedSize*100)/totalSize);
            }
            //close the output stream when done
            fileOutput.close();

    //catch some possible errors...
    } catch (MalformedURLException e) {
            e.printStackTrace();
    } catch (IOException e) {
            e.printStackTrace();
    }
4

1 回答 1

1

试试这个:

private String getExternalSDPath() {
    File file = new File("/system/etc/vold.fstab");
    FileReader fr = null;
    BufferedReader br = null;

    try {
        fr = new FileReader(file);
    } catch (FileNotFoundException e) {
       // handle
    }
    String path = null;
    try {
        if (fr != null) {
            br = new BufferedReader(fr);
            String s = br.readLine();
            while (s != null) {
                if (s.startsWith("dev_mount")) {
                    String[] tokens = s.split("\\s");
                    path = tokens[2]; // mount_point
                    if (Environment.getExternalStorageDirectory()
                            .getAbsolutePath().equals(path)) {
                        break;
                    }
                }
                s = br.readLine();
            }
        }
    } catch (IOException e) {
                // handle
    } finally {
        try {
            if (fr != null) {
                fr.close();
            }
            if (br != null) {
                br.close();
            }
        } catch (IOException e) {
           // handle                
        }
    }

    return path;
}

该代码是专门为具有内部、充当外部的内部和 SD 的三星设备编写的。

我需要访问 SD 并想出了上面的代码,所以你可以尝试它并可能修改它以在所有设备上工作。

编辑:我的下载 AsyncTask

    private class DownloadFile extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String filename = "somefile.pdf";

        HttpURLConnection c;
        try {
            URL url = new URL("http://someurl.com/" + filename);
            c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();
        } catch (IOException e1) {
            return e1.getMessage();
        }

        File myFilesDir = new File(Environment
                .getExternalStorageDirectory().getAbsolutePath()
                + "/Download");

        File file= new File(myFilesDir, filename);

        if (file.exists()) {
            file.delete();
        }

        if ((myFilesDir.mkdirs() || myFilesDir.isDirectory())) {
            try {
                InputStream is = c.getInputStream();
                FileOutputStream fos = new FileOutputStream(myFilesDir
                        + "/" + filename);

                byte[] buffer = new byte[1024];
                int len1 = 0;
                while ((len1 = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len1);
                }
                fos.close();
                is.close();

            } catch (Exception e) {
                return e.getMessage();
            }


        } else {
            return "Unable to create folder";
        }
    }

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
                .show();
        super.onPostExecute(result);
    }
}
于 2013-09-29T21:29:03.730 回答