Write to txt file, but not overwrite - android

I got a little problem, it seems simple (personally I think it is), but I couldn't find a answer. But atleast I don't know how to fix it.
I write some lines to a .txt file when I hit the button Save.
Then after that, when I type something else, and hit Save again, it overwrites my first lines.
But I want that it writes at a new line. Also when I close and restart the app again, and hit save again, it must save the text on a new line again.
So basically: How can I write text to a .txt file, without overwriting previous lines.
I can write to a file, so that is not the problem, but only how to NOT overwrite.
This is the "little" part of my code:
public void Data_save_contacts(View v) {
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
try {
writer_contact = new BufferedWriter(new FileWriter(root + "/Save/Contacten.txt"));
writer_contact.write("Perceel "+str_boer_teler_nummer+" = "+str_boer_teler);
writer_contact.newLine();
} catch (IOException e) {
System.err.println(e);
}
}
Please put me in the good directions.
Thanks already, Bigflow

You have to do
writer_contact = new BufferedWriter(new FileWriter(root + "/Save/Contacten.txt",true));
Just as said in java documentation:
FileWriter
public FileWriter(File file,
boolean append)
throws IOException
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
Parameters:
file - a File object to write to
append - if true, then bytes will be written to the end of the file rather than the beginning

try:
public FileWriter (File file, boolean append)
set the append to true

Well given this is just a little of your code (and I'm assuming you chunked it out so as to not reveal other parts) what I suspect is going on is that you're opening the file root + "/Save/Contacten.txt" in a non-append mode. The first time you call it the file is created and written to. Subsequent times you call it, it finds the file, and recreates (or deletes content) and then writes to it.
Try using:
writer_contact = new BufferedWriter(new FileWriter(root + "/Save/Contacten.txt", true));
Of course the first time you open/create the file you'll want it to be false (unless you ALWAYS want to append if the file already exists).
Give that a spin.

you can check for if file exits or not ?
or you can also append old file.
If not exits then and then only create new one.

Related

Saved data disappears from cell phone

I have made an app for Android which saves results for skeet shooting. During a session, the user either presses hit or miss. When the session is over, the user press save and the new result is appended to the json-object. After that the result is appended, it is saved to the phone via
public static void saveData(Context context) {
File path = context.getFilesDir();
File file = new File(path, "jsonUsr.json");
if (file.exists()) {
try {
FileOutputStream stream = new FileOutputStream(file);
String objString = usrObject.toString();
stream.write(objString.getBytes());
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now, my friend who has my app used it when we were at a competition today. During the session when my app was running and he had started to fill in his result, he receives an sms. He opens the message and reads it. Then instead of reopen my app from the current apps running, he goes to the meny and presses the icon. Suddenly he discovers that all data is gone! Not just the current session, but all results he has entered. I cannot understand that, because there does not even exists in the code a call which deletes the saved json string file.
I have tried to imitate what he did on my phone, but it works perfectly. He has had a lot of problems with the memory with his phone. For a couple of days ago, it complained about that there were not enough memory for upgrading, so he moved things to the SD-card? Is it possible that the data has either been removed due to lack of memory or that it is moved to the SD card?
It is not so much to work with, but I do not have more. Since I cannot recreate it myself, it is hard to know exactly what has happened.
It is a good idea to always write to a new file in the same directory. If that write succeeds, move the new file onto the config file by changing its name. (this change is atomic)
That way, you will always end up with a valid file, even if the call to write fails for some reason (out of disk, toString() fails, etc.).

File folder on Eclipse Android

I would like to make a xml file that will be modified during the execution of the application and i want to keep it after i close it for the next time i open it.
The first problem is that i don't know where do i have to put the file in the package explorer on Eclipse.
If i put the file on res/raw/ folder i could just read the file, but i can't modify.
I'm working with Jdom2.
The file is a score table for a game that will be modified every time the player finish a game.
That's the code i actually have to read the xml file stored on res/raw
try
{
puntf = getResources().openRawResource(R.raw.punt);
} catch (Exception ex)
{
Log.e("Ficheros", "Error");
}
And that's the code i actually have to modify the xml file(with Jdom2). But of course, that is wrong.
public void escritura()
{
try
{
xmlOutput.output(puntu, new FileOutputStream("punt.xml"));
}
catch (Exception e) {
e.printStackTrace();
}
}
Thanks a lot for your answers.
If you want to save a file and modify it programmatically I would suggest you to store it in this path:
/data/data/com.yourpackage.app/punt.xml
I have never worked with Jdom2, but you can have access to it by adding these lines of code:
File puntFile= new File("data/data/com.yourpackage.app/punt.xml");
FileOutputStream fos = new FileOutputStream(puntFile);
xmlOutput.output(puntu, fos);
You can also see the file in DDMS in file explorer. Just follow that path.
I can't understand if you want to save and edit the file during the process of your application or just save it somewhere before the app starts and edit it afterwords. If so, please give more details about that.
Hope I helped...
You should read uo on storage options on Andriod: THere's an article on this.... Use the resulting input and output streams for JDOM.

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(...).

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

Files are getting deleted from the SD card

I have developed a Service which will start when I receive the "ON_BOOTUP_COMPLETED" intent,
in "onCreate" of my Service I wrote the logic to create a text file in SD card of the device.
Below is the logic I have used to do so:
File abc = new File(Environment.getExternalStorageDirectory()+"\abc.txt");
if(!abc .exists())
abc.createNewFile();
abcwriter = new FileWriter(abc);
I am using "abcwriter" in other methods to write some content in to text file.
So far it is working fine.
But when rebooted the device, I observed that "abc.txt" file is creating again.
but I put a check before creating file "if(!abc .exists())". But still new file is created.
I suspect that when I rebooted the device my files are deleted. Is this the android behaviour..??
If it is please help me what I can do to make sure my files not created again.
You have to use the constructor below and pass true as the second parameter if you want to append to the file. Otherwise it will just get overwritten each time your code runs (when you reboot).Also get rid of the createNewFile() call, you don't need it since the writer will create it.
FileWriter(File file, boolean append)
abcwriter = new FileWriter(abc); -> this line (re)creates the file.
Make sure it's called only when needed:
File abc = new File(Environment.getExternalStorageDirectory()+"\abc.txt");
if(!abc.exists()) {
// abc.createNewFile(); -> this is not needed since following line handles this
abcwriter = new FileWriter(abc);
}

Categories

Resources