Permission denied: File created in .../files - android

I'm creating a file in data/data/myPackage/files/ :
file = new File( getFilesDir() + "/file.txt");
I'm absolutely sure that the file is created.
Right after its creation I call:
file.canWrite();
and the result is true.
When I try to use that file
I get: "Permission Denied".
In Eclipse, in DDMS, this file permissions are like:
-rw-------
Can anyone help here?
Thanks

Ensure you have the correct permissions to write to the file. In your manifest file, include this line
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />.

Easiest way to open the file (and create it at the same time) would be to use the openFileOutput("file.txt", MODE_PRIVATE) method.
This ensures that the file is only readable by your application (the same as you've have at the moment), plus it returns you a FileOutputStream so you can start writing to it.

The permissions look correct to me. Each application runs as a different user so only has access to it's own files.
When you say "I try to use that file" what do you mean? Can you post the code for that as I think that is where the problem lies.

If you know the file is being created using File() and you don't want to use openFileOutput() then try this:
FileWriter fWriter;
try {
fWriter = new FileWriter(file, true);
fWriter.write("hello");
fWriter.close();
} catch (IOException e) {
// log error
}

I have been working on the problem of nullpointerexception, file not found, for a few hours. I have moved from the emulator to an actual device. In the emulator the following worked:
BufferedWriter osw = new BufferedWriter(new FileWriter(path));
When I went directly to the device though, I got the exception.
Neelesh Gajender has hit the answer perfectly. Adding: :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in the android manifest solves this problem completely. I am grateful to Neelesh and Kudos!

I've found that for the writing on '/data/data/myPackage/files/',
permissions need to be set.
There was MODE_WORLD_WRITEABLE,
that was the one with interest for this case,
but even with this permission set, I still got error.
I thought: "maybe what I need is an EXECUTE permission...".
There is no such permission in the API
but even though I tried to put a 3 in the mode parameter
(MODE_WORLD_WRITEABLE is = 2),
and...it worked!
But when I write to the sd card with that permission set,
I get an error as well,
so I write differently to the two folders.
int permission = 3;
if (whereToWrite == WRITE_TO_DATA_FOLDER) {
FileOutputStream fos = openFileOutput(file.getName(), permission);
buffOutStream = new BufferedOutputStream(fos);
} else if (whereToWrite == WRITE_TO_SD_CARD){
buffOutStream = new BufferedOutputStream(new FileOutputStream(file));
}
And by the way,
MODE_WORLD_WRITEABLE is wrong,
MODE_WORLD_WRITABLE is right.

Related

How to use JaudioTagger to write data?

I am trying to use JaudioTagger 2.2.3 to edit tags of audio file but till now i have not achieved any success.
this is a test code to change the Artist tag of a mp3 file in Internal Storage
String path;
try
{
TagOptionSingleton.getInstance().setAndroid(true);
AudioFile f=AudioFileIO.read(new File(path));
Tag t=f.getTag();
t.setField(FieldKey.ARTIST,Str);
AudioFileIO.write(f);
}catch(CannotReadException e){}
catch(TagException e){}
catch(ReadOnlyException e){}
catch(InvalidAudioFrameException e){}
catch(CannotWriteException e){}
My Application is well elevated with android.permission.WRITE_EXTERNAL_STORAGE and android.permission.READ_EXTERNAL_STORAGE
I am testing in Android version Android 6.0
this code throws InvalidAudioFrameException with a message
No audio header found within example.mp3
Its not that the audio is corrupt as it shows similar error with other mp3s also
Also if any one has any other wat for audio tagging please do tell me and i have also used mp3agic which repeadedly shows:example.mp3:open failed :EROFS(Read only file system) on the line
Mp3File mp3file = new Mp3File(filePathStr+"example.mp3");
ID3v1 id3v1Tag;
if (mp3file.hasId3v1Tag()) {
id3v1Tag = mp3file.getId3v1Tag();
} else {
// mp3 does not have an ID3v1 tag, let's create one..
id3v1Tag = new ID3v1Tag();
mp3file.setId3v1Tag(id3v1Tag);
}
id3v1Tag.setTrack("5");
id3v1Tag.setArtist("An Artist");
id3v1Tag.setTitle("The Title");
id3v1Tag.setAlbum("The Album");
id3v1Tag.setYear("2001");
id3v1Tag.setGenre(12);
id3v1Tag.setComment("Some comment");
mp3file.save("example.mp3")//error showing in this line
My question
How to rectify Jaudiotagger?
Is there any way to use Mp3agic as an alternative to Jaudiotagger?
Or there is any other efficient way leaving these two?
I have also used JaudioTagger-android but same problem persists.
thanks in advance!
For the error when doing
mp3file.save("example.mp3")
i would recommend to not overwrite directly the old file. Try to create a new file, and then delete and rename to restore the original file setup.
song.save(location + "intermed");
File from = new File(location + "intermed");
File file = new File(location);
file.delete();
File to = new File(location);
from.renameTo(to);
Of course you need to add exception handling and what not, and also this will fail if you have no write permissions. This may be the case if you use a more recent Android version, i think above 4.4, and you try to access the SD card. Then, the write permissions need to be granted at runtime for specific folders, the manifest write permission is not sufficient. See Android's Storage Access Framework.

Trying to save a file on an android system and make it downloadable by the user

I am sorry I am extremely new to android and I am lost. I successfully found out how to save a file on an android system, but every time I try to search for the file on my Android phone (which is where I have a copy of this app located) I am unable to locate it. I know it is there because the app would not start up with out it. How do you write a file that can be both used by the App AND searched by the user in the File Explorer. I am using a Galaxy Note 3 Android version 5.0 Any help would be appreciated.
private void WriteFile(String FileName, String FileCont, boolean isAppend){
File file = new File(getApplicationContext().getFilesDir().getAbsolutePath() + "/" + FileName);
try {
FileOutputStream stream = new FileOutputStream(file, isAppend);
stream.write(FileCont.getBytes());
stream.close();
}
catch(Exception ex){
}
}
Did set the permissions to write on external space in your manifest.xml?
For reference see
http://developer.android.com/reference/android/Manifest.permission.html
You have to set the "WRITE_EXTERNAL_STORAGE" permission to write on external disk. Just add the following line to your android manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It will implicitly contain the permission to read external storage as well ;).

How to create a file of specific size on sd card programatically

Can some one please let me know how to create a file of specific size on sd card programatically.
I did tried shell command like this which is of no use,
try {
Process p = Runtime.getRuntime().exec("dd of=/mnt/extSdCard/output.dat bs=1 seek=1M count=0");
} catch (IOException e1) {
}
I did even try the same command in shell script and was not able to create the file.
I guess since my device is not rooted, this command did not work.
Any help regarding this highly appreciated.
-regards,
Manju
you can use RandomAccessFile as shown here.
First you obtain prermission for External storage.
Edit the AndroidManifest.xml with the following line of code.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
After that in java file write the following code.
File fileName = new File(Environment.getExternalStorageDirectory(),
"output.dat");
FileOutputStream fos = new FileOutputStream(fileName )
fos.write(bytes);

IllegalArgumentException while writing on sdcard

I saw this problem has been met many times, but strangely I was not able to find a solution.
I am trying to write a binary file to the SDcard. This is the source code:
private void saveDataLongs() {
try
{
ObjectOutputStream oos = new ObjectOutputStream(ctx.openFileOutput(Environment.getExternalStorageDirectory().getAbsolutePath()+"/longs.bin", ctx.MODE_WORLD_WRITEABLE));
for (int w=0; w<longCount; w++)
oos.writeLong(longs[w]);
oos.close();
}
catch(IOException e)
{ e.printStackTrace(); }
}
The Manifest contains
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and I receive this error:
01-21 22:19:57.323: E/AndroidRuntime(13713): java.lang.RuntimeException: Unable to start activity ComponentInfo{it.ccc.ccc/it.ccc.ccc.Ccc}: java.lang.IllegalArgumentException: File /sdcard/longs.bin contains a path separator
From other posts I could understand that some functions are meant to write only in the private storage of the app, so they don't expect to manage directories and paths.
Is some one able to help me? Whall I use a different method to write the data to the sd, or just make some other action before doing it? I'm trying to write to the sdcard a simple binary file (btw it's a precalculated sequence of number, and I need to pass it to my PC and then move it back to the assets, so, if there is a different way to obtain this goal, it's ok anyway).
Thank you very much.
You say that you are trying to write to external storage, but you are calling openFileOutput(), which is for internal storage.
Change:
new ObjectOutputStream(ctx.openFileOutput(Environment.getExternalStorageDirectory().getAbsolutePath()+"/longs.bin", ctx.MODE_WORLD_WRITEABLE));
to:
new ObjectOutputStream(new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "longs.bin")));
or, better yet, to:
new ObjectOutputStream(new FileOutputStream(new File(ctx.getExternalFilesDir(null), "longs.bin")));
I like CommonsWare's answer. I would simply like to add that if you ever DO want to go down a path, don't use /. Use File.separator. I don't think I've ever had any errors come up when simply using / but still.
So if you made a sub-folder called "To-dos" in the sdcard's directory, you would do something like the following:
new ObjectOutputStream(new File(Environment.getExternalStorageDirectory() + File.separator + "To-dos", "longs.bin"));

It can't access the sdcard after setting "android.uid.system" in my application?

This is a strange problem. My Application can access the sdcard successfully if I don't set android.uid.system to it. But after setting android.uid.system to it, my application can't access the sdcard. At this time, the exception take place:07-13 09:11:24.999: INFO/System.out(9986): create file happen exception--->java.io.IOException: Permission denied. I check I write the right permission in the right place:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />.
Because use forceStopPackage in my application, I need to add android.uid.system to the manifest. And I have written LOCAL_CERTIFICATE := platform in the make file. Who can explain this strange problem. After setting android.uid.system, my application is belong the system process which should have more power to access the sdcard. This is my idea. The following are my code:
public void setPackage(String dir){
System.out.println( "setPackage dir=="+dir );
File share=new File("/mnt/sdcard","test.txt");
if(!share.exists()){
try{
share.createNewFile();
}catch(Exception e){
System.out.println( "creat file happen exception--->" +e.toString() );
}
}
try{
if(share!=null){
System.out.println( "create file is not null" );
FileOutputStream fops=new FileOutputStream(share);
fops.write(dir.getBytes());
fops.flush();
fops.close();
}
}catch(Exception e){
System.out.println( "write Exception-->" +e.toString() );
}
}
And My application run at the emulator and his target version is 2.3. Thank you very much.
Please read this: link1
and this link2
Use Environment.getExternalStorageDirectory().getAbsolutePath() to get the path, NOT "/mnt/sdcard"
Use: File share = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"test.txt");
This won't work: File share = new File("/mnt/sdcard", "test.txt");
You can see in android source code: frameworks\base\core\java\android\os\Environment.java, it have a function:
private static void throwIfSystem() {
if (Process.myUid() == Process.SYSTEM_UID) {
Log.wtf(TAG, "Static storage paths aren't available from AID_SYSTEM", new Throwable());
}
}
This function would be called getExternalStorageDirectory(), hence app with system uid can't access sdcard if you don't hack aosp.
android.uid.system make your app bind system, but sdcard observered by system also, then if your app delete this, it can access the sdcard. it seems
delete this line in your xml file :android:sharedUserId="android.uid.system"ystem

Categories

Resources