简体   繁体   中英

Writing ArrayList of objects to external storage

I'm trying to save arraylist of objects to external storage, but I get this message:

java.io.FileNotFoundException: /storage/1917-121E/Documents/chem/bazaChem.dat: open failed: ENOENT (No such file or directory).

I do have permission in manifest file. Here is my code:

public void saveToSD(ArrayList<Chemical> bazaChem)
{
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+"/chem";
        try {
            File dir = new File(path);
            if(!dir.exists())
            {
                dir.mkdir();
            }
            OutputStream fos = null;
            ObjectOutputStream oos = null;
            File plik = new File(path, "bazaChem.dat");
            fos = new FileOutputStream(plik);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(bazaChem);
            oos.close();
            Toast.makeText(AddDataPanel.this, "Zapisałem bazę na karcie SD!!!", Toast.LENGTH_LONG).show();
        } catch(Exception ex) {
            ex.printStackTrace();
            System.out.println(ex.getMessage());
            Toast.makeText(AddDataPanel.this, "Wyjątek!!!", Toast.LENGTH_LONG).show();
        }
    }


}

Any idea what is the problem?

You need to explicitly request permission to write external storage on sdk23 and any device running api23 and up. The permission WRITE_EXTERNAL_STORAGE was moved to dangerous protection level and user must explicitly agree to that. You need to request check of self permission to display permission dialog for the user and iterate through result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM