IllegalArgumentException while writing on sdcard - android

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"));

Related

How can I write a public file for my service to pick up on Android?

I have two parts to this question: 1) what is the best solution to my need, and 2) how do I do this?
1) I have a client app which sends bundles to a service app. the bundles can break the limit on bundle size, so I need to write the actual request out and read it in on the service side. Because of this, I can't write to my private internal storage. I've used these pages heavily, and haven't had luck: http://developer.android.com/guide/topics/data/data-storage.html
http://developer.android.com/training/basics/data-storage/files.html
My current understanding is that my best path is to use this to get a public dir:
File innerDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
I then add in my filename:
String fileName = String.valueOf(request.timestamp + "_avoidRoute"+count+++".ggr");
Combing these two results in the full file path:
/storage/emulated/0/Download/GroundGuidance/Route/1425579692169_avoidRoute1.ggr
Which I write to disk like this:
fos = context.openFileOutput(fullPath, Context.MODE_WORLD_WRITEABLE);
fos.write(routeString.getBytes());
fos.close();
When I try to write this to disk I get the error
java.lang.IllegalArgumentException: File /storage/emulated/0/Download/GroundGuidance/Route/1425579692169_avoidRoute1.ggr contains a path separator
Of course it does - I need it to have a path. I've searched online for solutions to this error which tell me to us FileOutputStream to write a full path. I did, but while my app doesn't error and appears to create the file, I'm also not able to view it on my phone in Windows Explorer, leading me to believe that it is creating a file with private permissions. So this brings me to my post and two questions:
1) Is there a different approach I should be trying to take to share large amounts of data between my client and service apps?
2) If not, what am I missing?
Thanks all for reading and trying to help!
Combing these two results in the full file path:
/storage/emulated/0/Download/GroundGuidance/Route/1425579692169_avoidRoute1.ggr
Which I write to disk like this:
fos = context.openFileOutput(fullPath, Context.MODE_WORLD_WRITEABLE);
This is not an appropriate use of Context's openFileOutput() method as that does not take a full path, but rather a filename within an app's private storage area.
If you are going to develop a full path yourself, as you have, then use
fos = new FileOutputStream(fullPath)
The Sharing permission setting is not applicable to the External Storage, though you will need a manifest permission to write (and implicitly read) on your creator, and the one for reading on your consumer.
Or, instead of constructing a full path, you could use your private storage with a filename and Context.MODE_WORLD_WRITEABLE (despite the being deprecated as an advisory) and pass the absolute path of the result to the other app to use with new FileInputStream(path).
Or you could use any of the other data interchange methods - content providers, local sockets, etc.

Outputting a txt file to a folder in internal memory in android

I am in need to create a text file where the input is taken from the user.
I am trying to save the txt file in a folder(folder should be created even if it is not there)
My code is as follows,
FileOutputStream fileos = null;
if (FreeMemory() != 0) {
FileOutputStream fos=null;
try {
File path=new File(getFilesDir(),"sri");
if(!path.exists()){
path.mkdir();
}
File mypath=new File(path,"myfile.txt");
if (!mypath.exists()) {
fos = new FileOutputStream( mypath);
String text="Write Hii";
fos.write(text.getBytes());
fos.close();
}
}catch(Exception e){
}
}
The "path" variable gives this path: "/data/data/com.example.gm/files/sri"
I navigated to this path in my device: Android-->Data-->com.example.gm-->files-->
but the folder "sri" is not created and even the file also. Am I navigating to th ecorrect path ? I am not able to find out the file in the device.
I searched for the folder by installing "Astro File Manager" app too. But, couldn't find it. I am not getting any Exception when writing to the folder. The code must be correct. But where is the folder and file? Please anyone help me in solving this.
I want to save the txt file in internal memory of my device.
Whats wrong with my code? Please suggest me the solution.
I have gone through many trails and finally approached stackoverflow.
Thanks for any help!!
The data in the internal storage is not accessible out side the application owning it, so any third party application like file browser or Astro File Manager will not be able to see the files. The application with root access will only be able to access the files in the internal memory. I believe you should programmatically verify if the file is created. getFilesDir() will give the internal memory location allocated to that app.
Have you give the permission in manifiest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Check if a file has been written to in Android

I have a question about Android programming. Basically, I am unsure of where to check where my file is, and if I wrote to it correctly. I want to locate where the file is, and I also want to know whether or not I wrote to it correctly. Below is the code I have come up with:
String lsNow = "testing";
try {
fos = openFileOutput("output.txt", Context.MODE_APPEND);
fos.write(lsNow.getBytes());
fos.close();
}
catch{
...
}
Where can I find output.txt? Might anyone know how to check this all out? if so, that would be great! I am using an emulator by the way. If I were to do this on a real Android, how would one approach this also? (Just for future reference)
You Test it in Two ways
Using File Explorer
Go to DDMS perspective--> Open File Explorer-->location of the file
Pragrammatically by using exits() method
File file = new File(context.getFilesDir(), filename);
if(file.exists())
Using openFileOutput(...) means the file will be written to internal storage on the Android device in an area which is secure from access by other apps.
If you want to make sure the file is written correctly then make sure your catch block handles any failures (if it is called then the file writing has failed).
To access the file once it has been written use openFileInput(...).

How to read file that belongs to other app from external storage?

I want to read text file, that was written by other my app. It's saved ad "Android/data/MyPackageName/files/"
I use this code:
File file = new File("//Android//data//MyPackageName//files//", "filename.txt");
FileInputStream is = new FileInputStream(file);
but i get exception "no such file or directory"
I am sure that solution is pretty simple, but i can't find it yet.
Thank you for your help!
I don't think it is right to use the double backslash "//", one is enough. Also, the path should be "/mnt/sdcard/Android/data....". I am not sure the "/mnt/sdcard" is applicable on every device, so my suggestion is to use Environment.getExternalStorageDirectory to get the root dir on sd card.

Permission denied: File created in .../files

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.

Categories

Resources