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);
}
Related
I'm storing user data in ApplicationData folder. Its path is obtained with :
userDataPath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), "userData");
This variable is equal to /data/user/0/APPNAME/files/.config/userData.
Each time I rebuild the project, if I delete the userData file with File.Delete(userDataPath), I can successfully create the file, write and read to it several times. I can indeed check the created file in /data/data/APPNAME/files/.config/userData.
I check in /data/data/.../.config/userData and not in /data/user/.../.config/userData because apparently the latter is a symlink to the former, so it should be equivalent ? Moreother I don't have access to /data/user/.../.config/userData.
The problem is that if I rebuild the app without deleting the file, I got an unhandled exception at the following Deserialization (which worked fine before) :
if (File.Exists(userDataPath))
{
Stream reader = new FileStream(userDataPath, FileMode.Open);
Console.WriteLine(userDataPath);
userData = (UserData)serializer.Deserialize(reader); // ERROR HERE
reader.Close();
}
It is very strange because the file located at /data/data/APPNAME/files/.config/userData does not exist but since File.Exists(userDataPath) is true, the file located at /data/user/0/APPNAME/files/.config/userData does exist.
So how can this be explained and is this the correct way to store data in ApplicationData folder ?
After switching to another SpecialFolder (LocalApplicationData), I can't reproduce the unhandeld exception anymore (even when switching back to ApplicationData).
I'll keep this post updated if it ever happens again.
I have a simple app with a button. I have a FileOutputStream defined globally in the MainActivity. Then on the onCreate() I initialize it. When the button is clicked, I open a new file output like:
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes()); outputStream.close();
Sorry if the question sounds dumb, but does this code inside the button click listener create a new different file each time I click on the button? Like if I click 10 times to that button will I have 10 files in the actual app file directory?
This concern comes because I realised the app keeps increasing its size when I check it on the internal storage settings.
Is there any way to ensure that the file is only going to be created just on the first button click? Like creating it only if it hasn't been created yet.
Thanks.
If your filename remains same, it will create the file for the first time and then open it again and again on subsequent button clicks. Take a look here in the official documentation:
Open a private file associated with this Context's application package
for writing. Creates the file if it doesn't already exist.
You need only one file name not have any other name
or
You can use check File exiting before create it again, try this code:
File f = new File(filename); //file path
if (!f.exists()){
//do your code to create new file
}
I have read a ton of articles on writing to the internal storage of an android device, and I need some help figuring out what I am doing wrong. In the main activity of my app, I read a value from a file stored in the internal storage like this:
string ID = GetID();
Where GetID looks like this:
string GetID()
{
try
{
using (var i = new StreamReader (OpenFileInput (FILENAME)))
{
return i.ReadToEnd();
}
}
catch
{
return "";
}
}
If the file doesn't exist, "" is returned and the user is sent off to another activity to register. In that activity, I use this to call a function to write to internal storage like this:
WriteID (uniqueID);
Where WriteID looks like this:
void WriteID(string uniqueID)
{
using (var o = new StreamWriter (
OpenFileOutput (FILENAME, FileCreationMode.Private)))
o.Write (uniqueID);
}
This is where it gets weird for me, if I put these two functions in the same activity, write to the file and then call the function to read from it, I get uniqueID returned correctly. However if I stop the app and then restart it, I get a File Not Found exception thrown and nothing returned from the read function. However, if I create a new project, and use the same code, everything works as expected (file is created and written to, then on restart the data persists).
So I am thinking there is some setting that I have changed or some reference that I may be missing in my original app that causes the internal storage file to be removed when the app is stopped?
Any ideas as to why this works correctly in my test app, but not in the other?
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(...).
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.