Check if a file has been written to in Android - 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(...).

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.

Android create file without saving

File tempFile = File.createTempFile(""+Common.getMobileNumber(), ".jpg", null);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(bos.toByteArray());
I do this, but thing is ...when i go to apps, and click on my app... i see that its adding caching. and this particular file is caching, how can i create file without caching/saving.
only need of file for me, is to send it over to server side. Is there any way i create a object file without saving/caching?
If you are saying you need like a file only in the memory for the particular task like uploading to server. It is very similar to this question to do that. There is a code to create a file in memory.
Android Creating a memory resident input file that can be attached to an email

ANDROID internal storage file delete/exist not working for me

First of all, I want to know if making a file without extension is okay. For example, making a file with ".txt" extendsion will make it a txt file on a computer, but I don't know it matters in android. And I noticed that when working on eclipse, I could deleted a fild with the extensions but couldn't delete a file without a extension.
I want my program to delete a file in the internal storage (com.name.application folder) but it's not working for me.
I make a file with
FileOutputStream fos = openFileOutput(FileName, MODE_PRIVATE);
write with
bos = new BufferedOutpuStream(openFileOutput(FileName,Context.MODE_APPEND)
bos.write(newVocabFile.getBytes());
and I want to delete with
FILE file = new File(fileName);
fild.delete();
I did researches on google and applied different methods to my codes, but every method did not work for me. Because .delete() does not work properly, .exist() does not work either. I tired making the mile with and without extension but both ways did not work either.
I really need to get through this in order to finish my application. Please help me
You have a typo on this line
FILE file = new File(fileName);
fild.delete();
It should be
File file = new File(fileName);
file.delete();

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

Using 'FileWriter' to Write to a Text File on an SD Card in Android

I've researched this problem for a while now and I've only found really complicated answers so I'm very confused. Keep in mind that I'm not an expert programmer so don't expect me to know a ton about this!
All I want to do is print a new line of characters to a text file located in the downloads folder of an SD card in Android. I set up my emulator to have an SD card and placed the text file in the downloads folder. This piece of code is for a database class that will access a text file in an SD card to read the data. I know that the class works outside of Android so assume that all of the methods are working as they should to read the data!
I get an IOException when I run this method in another class:
public void addRecordToDataBase(ChildRecord c) throws IOException
{
FileWriter outFile = new FileWriter("/mnt/sdcard/download/database.txt");
PrintWriter out = new PrintWriter(outFile);
out.println(c.printToDataBase());
out.close();
}
The weird thing is I can read from the database just fine in other methods using that same path; no problems there. I just can't write to it. I've read somewhere that you can use "regular Java methods" to write to an SD card in Android without those crazy "OutputStream" things all over the place. Is this true? I debugged this thing and found out that the line of code that is throwing the exception is right here:
FileWriter outFile = new FileWriter("/mnt/sdcard/download/database.txt");
If anyone has any idea why I'm geting this IOException, I would be really grateful! I did try all the crazy methods that Android wants to use but I think I got lost in it so I just reverted back to what I knew how to do.
Thank you so much!
My guess is you can't access such directory with writing permissions, at least in that manner.
Did you take a look at http://developer.android.com/guide/topics/data/data-storage.html#filesExternal?
That reference and this one (http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)), explaining how getExternalFilesDir works, may be of help to you!
Have you declared the WRITE_EXTERNAL_PERMISSION permission in your apps manifest file?

Categories

Resources