ikevin8me
ikevin8me

Reputation: 4313

How to I write to the external storage from an Android app?

I'm trying to write some code to stream a file from a server directly into the Android external storage system.

    private void streamPDFFileToStorage() {
    try {
        String downloadURL = pdfInfo.getFileServerURL();
        URL url = new URL(downloadURL);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        InputStream pdfFileInputStream = new BufferedInputStream(httpURLConnection.getInputStream());
        File pdfFile = preparePDFFilePath();
        OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));
        byte[] buffer = new byte[8012];
        int bytesRead;
        while ((bytesRead = pdfFileInputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, bytesRead);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private File preparePDFFilePath() {
    File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
    dir.mkdirs();
    File file = new File(dir, "filename");
    return file;
    /*
    String pdfFileDirectoryPath = ApplicationDefaults.sharedInstance().getFileStorageLocation() + pdfInfo.getCategoryID();
    File pdfFileDirectory = new File(pdfFileDirectoryPath);
    pdfFileDirectory.mkdirs();
    return pdfFileDirectoryPath + "/ikevin" + ".pdf";
    */
}

It keeps getting an exception of "No such file or directory" at

"OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));"

How do I write the file? What's wrong with my code? (Also, I am not using Context.getExternalFilesDir() because I don't know how to get the Context from my controller logic code. Can anyone advise if this is the better solution?)

Upvotes: 0

Views: 1019

Answers (2)

Robin Chander
Robin Chander

Reputation: 7425

new File is returning you a file object and not the file. You might wana create a file before opening a stream to it. Try this

File pdfFile = preparePDFFilePath();
boolean isCreated = pdfFile.createNewFile();
if(isCreated){
   OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));
}

Upvotes: 2

StarsSky
StarsSky

Reputation: 6711

This code works:

    String root = Environment.getExternalStorageDirectory().toString();
    File dir = new File(root + "/dir1");    
    dir.mkdirs();

Upvotes: 0

Related Questions