1

I'm working on an app that gets data over BLE and saves it in a text file.

The problem now is that I'm not able to create a text file with my app.

I've already tried the answers from this thread: How to create text file and insert data to that file on Android So please don't mark it as duplicated, cause the answers provided there won't work for me..

The corresponding code is:

try {
        System.out.println(Environment.getExternalStorageState());
        File root =new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "BLE_Crawler");
        if (!root.exists()) {
            root.mkdirs();

        }
        File file = new File(root, fileName +".txt");
        if (!file.exists()) {

                file.createNewFile();

        }
        FileWriter writer = new FileWriter(file, true);
        writer.append("test");
        writer.flush();
        writer.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

And the error I get is:

W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Documents/BLE_Crawler/test.txt: open failed: ENOENT (No such file or directory)

It seems that I don't have the rights to make a new folder cause the "mkdirs()" line doesn't work. But I don't know how to fix this problem.

Oh and I have

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

in my AndroidManifest.

I'm using SDKVersion 29.

Grogak
  • 27
  • 6

1 Answers1

1

Have you tried adding:

    android:requestLegacyExternalStorage="true"

to your manifest in <application> tag? Also, don't forget that from Android 6.0 you need to request permissions even if you write them in your Manifest.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        String[] permissions = new String[]{READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE};
        for (int i = 0; i < permissions.length; i++) {
            if (checkSelfPermission(permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(permissions,
                        REQUEST_PERMISSIONS);
                return;
            }
        }
    }
Dan Baruch
  • 1,063
  • 10
  • 19
  • @Grogak no problem. I'd recommend reading https://developer.android.com/training/data-storage/use-cases as this should be a temporary solution. – Dan Baruch Oct 22 '20 at 13:07