简体   繁体   中英

Android reading and writing files to internal storage

I've got a problem with reading and writing files to the internal storage.

These are the methods i use to write/read files:

public static void writeFile(String fileName, String data) throws IOException {
    File file = new File(activity.getFilesDir() + "/" + fileName);
    file.getParentFile().mkdirs();
    if (file.exists())
        file.delete();
    file.createNewFile();
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(data.getBytes());
    fos.close();
}

public static String readFile(String fileName) throws IOException {
    FileInputStream fis = new FileInputStream(new File(activity.getFilesDir() + "/" + fileName));
    InputStreamReader isr = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(isr);
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();
    while (line != null) {
        sb.append(line);
        line = br.readLine();
    }
    fis.close();
    return sb.toString();
}

This works:

writeFile("fileName", "someData");
readFile("fileName");

but this doesn't:

writeFile("directory/filename", "someData");
readFile("directory/filename");

For some reason I get a FileNotFoundException: (No such file or directory)

I tried some other methods, but nothing work with paths.

check write or read - storage permission in AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Or try like this in your code

`File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/EmailClient/");

folder.mkdirs(); File file = new File(folder,filename); file.createNewFile();`

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