I tried to make 'File Control' app.
I can't find how to write file. I set permission like this.
AndroidManifast.xml
<application
...
android:requestLegacyExternalStorage="true"
...
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
and i call this code in MainActivity.onCreate.
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MODE_PRIVATE);
verifyStoragePermissions(this);
I want read and write file, at /storage/3066-3133/title.txt . /storage/3066-3133 is my sdcard path.
read file is work perfectly.
public void readFile() {
String fileTitle = "title.txt";
File file = new File("/storage/3066-3133", fileTitle);
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String result = "";
String line;
while ((line = reader.readLine()) != null) {
result += line;
}
popupToast("read : " + result);
reader.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
popupToast("no file found");
} catch (IOException e2) {
e2.printStackTrace();
popupToast("read fail");
}
}
but write code occur exception. write Exception: /storage/3066-3133/title.txt: open failed: EACCES (Permission denied)
public void writeFile() {
String fileTitle = "title.txt";
File file = new File("/storage/3066-3133", fileTitle);
try {
if (!file.exists()) {
file.createNewFile(); // error!!!!
}
FileWriter writer = new FileWriter(file, false);
String str = " write text ";
writer.write(str);
writer.close();
} catch (IOException e) {
e.printStackTrace();
popupToast("write fail");
}
}
Do i need more permission for sdcard?
or this is problem? First, i create project for target sdk:31. and i change 29 in build.gradle. changing target sdk is not work?