My application can create a file, but cannot read it.
I am writing a file in internal memory:
byte[] data = ... // (A buffer containing wav data)
String filename = context.getFilesDir().getAbsolutePath() + "/newout.wav";
File file = new File(filename);
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
Then I try to reproduce it:
MediaPlayer player = new MediaPlayer();
player.setDataSource(filename);
player.prepare();
player.setLooping(false);
player.start();
But crashing prepare()
:
java.io.IOException: Prepare failed.: status=0x1
I checked the file and saw that it was the permission -rw-------
. I changed it to -rw-r--r--
, after which it was successfully reproduced.
So how can my application write a file but can't read it? And how can I make it FileOutputStream
set the rights correctly?
source to share
To change programmatic file permissions -rw-rr--, you need to do something like this:
Process process = null;
DataOutputStream dataOutputStream = null;
try {
process = Runtime.getRuntime().exec("su");
dataOutputStream = new DataOutputStream(process.getOutputStream());
dataOutputStream.writeBytes("chmod 644 FilePath\n");
dataOutputStream.writeBytes("exit\n");
dataOutputStream.flush();
process.waitFor();
} catch (Exception e) {
return false;
} finally {
try {
if (dataOutputStream != null) {
dataOutputStream.close();
}
process.destroy();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
source to share
If you open a file, the default mode is Context.MODE_PRIVATE
eg. how in
File file = new File(context.getFilesDir(), filename);
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
(taken from the documentation ). The modes are MODE_WORLD_READABLE
both MODE_WORLD_WRITABLE
deprecated and do not work on newer devices. Therefore, I would say that it is better to write to external storage so that the content is available to other applications.
Note: according to the documentation :
External storage: "It is readable in the world, so files stored here can be read outside of your control."
source to share