1. Add permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2. Add application node in AndroidManifest.xml
android:requestLegacyExternalStorage="true"
3. Dynamically apply for permissions in the code
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
4. Read and write code
public static void writeToFile(byte[] bytes, String path) {
String SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
path = SDCardRoot + path;
File f = new File(path);
if (!f.getParentFile().exists())
f.getParentFile().mkdirs();
if (bytes!=null) {
try (FileOutputStream out = new FileOutputStream(path))
{
out.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static byte[] readFromFile(String path) {
String SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
path = SDCardRoot + path;
File f = new File(path);
if (!f.isFile() || !f.exists())
return null;
long len = f.length();
try (InputStream in = new FileInputStream(path))
{
byte b[]=new byte[(int) len];
in.read(b);
return b;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}