Appending data to a text file in Android - android

I am trying to add data to a text file in android using the code below but it only overwrites the data with one line of data.
private void copyImageToMemory(File outFile , Float number) {
try {
BufferedOutputStream fos = new BufferedOutputStream(
new FileOutputStream(outFile));
PrintWriter pw = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(fos)));
pw.append("result"+number);
pw.close();
maxSpeed=0;
} catch (FileNotFoundException e) {
Log.e(TAGFile, "FileNotFoundException");
}
}

The FileOutputStream constructor allows to specify whether it should append to an already existing file or not:
new FileOutputStream(file, true);
will create a stream that appends to the given file.

Related

FileNotFoundException although the text file exist (readable and writable)

I am trying to save data into text file in the internal storage and read it again .. It works fine in my mobile with android 11 but when i tried at android 8 it gives me this error
java.io.FileNotFoundException:/data/user/0/com.example.example/test.txt
(No such file or directory)
It appears at the first time to open the activity but i can clear it - as normal text - and write a new text and save it so the file is there and usable
here is read code
File path = getApplicationContext().getFilesDir();
File readFrom = new File(path, fileName);
byte[] content = new byte[(int) readFrom.length()];
try {
FileInputStream stream = new FileInputStream(readFrom);
stream.read(content);
return new String(content);
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
and this write code
public void writeToFile(String fileName, String content) {
File path = getApplicationContext().getFilesDir();
try {
FileOutputStream writer = new FileOutputStream(new File(path, fileName));
writer.write(content.getBytes());
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Write data continuously to file in external storage - Android App

I am writing the data to the file in an external storage (SD card) on my android. The issue that I am facing is that it just makes one entry and does not go beyond that. I have looked up a number of Q/As here. Could someone please point me in the write direction? TIA!
FileOutputStream outputstream;
try {
file1 = new File(Environment.getExternalStorageDirectory(), "MyData.txt");
outputstream = new FileOutputStream(file1);
OutputStreamWriter oswriter = new OutputStreamWriter(outputstream);
BufferedWriter bwriter = new BufferedWriter (oswriter);
bwriter.append(entry);
bwriter.newLine();
bwriter.close();
outputstream.close();
} catch (Exception e) {
e.printStackTrace();
}
You have to tell FileOutputStream to append the data. By default it just overwrites all contents there. For this you only need to use a different constructor FileOutputStream(File, boolean):
outputstream = new FileOutputStream(file1, true);

Android write text in file Sd card

i try to write text in file.i wrote code ,witch can to write text ,but if i will use again my code again text is rewrite in file.for example if i first time write "Hello android" and then "Sir",result is only "Sir".i want "Hello android Sir"
your_file = new File("/sdcard/facebookUser");
try {
Writer writer = new OutputStreamWriter(new FileOutputStream(
your_file), "UTF-8");
writer.write(facebook_user_name + ",");
writer.write(facebook_id);
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
how i can write code to save another text in this file second time?
new FileOutputStream(your_file, true)
public FileOutputStream(String name, boolean append) throws FileNotFoundException
append - if true, then bytes will be written to the end of the file rather than the beginning
Instead of:
writer = new OutputStreamWriter(new FileOutputStream(
your_file), "UTF-8");
Use:
writer = new OutputStreamWriter(new FileOutputStream(
your_file, true), "UTF-8");
This sets the FileOutputStream in append mode.
java.io.FileOutputStream.FileOutputStream(File file, boolean append)
throws FileNotFoundException
Constructs a new FileOutputStream that writes to file. If append is
true and the file already exists, it will be appended to; otherwise it
will be truncated. The file will be created if it does not exist.
try {
int n = 0;
String Name = "file";
File myFile = new File("/sdcard/test/");
if (!myFile.exists()) {
boolean b = myFile.mkdirs(); }
myFile = new File("/sdcard/test/"+Name+".txt");
while (myFile.exists())
{
myFile = new File("/sdcard/test/"+Name+n+".txt");
n++;
}
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
String str = "Your text to write";
myOutWriter.append(str);
myOutWriter.close();
fOut.close();
} catch (Exception e) {}
And do not forget permision:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Vladimir Kulyk and user2450263 are correct! You have to write a file in append mode. try this link.

Why does my old file contents get overwritten?

i'm using the below code to save log data to a file.
However, every time a new call is made, the old content is gone.....
i can't figure out what the issue is however....
public void writeToFile(String fileName, String textToWrite) {
FileOutputStream fOut = null;
try {
File root = new File(Environment.getExternalStorageDirectory() , fileName);
if (! root.exists()){
root.createNewFile();
}
fOut = new FileOutputStream(root);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(textToWrite);
myOutWriter.flush();
myOutWriter.close();
}
catch (Exception e) {
new MailService().mailMessage(e.toString());
}
finally{
if(fOut != null){
try{
fOut.close();
}
catch(Exception ex){
}
}
}
}
You need to pass second parameter boolean true to FileOutputStream constructor which indicates the file will be opened in append mode rather than write mode.
FileOutputStream out=new FileOutputStream("myfile");
Everytime you execute the above code it will open the file in write mode so that the new content will overwrite the old content. However, the FileOutputStream constructor accepts a second argument which is a boolean indicating whether to open the file in append mode.
FileOutputStream out=new FileOutputStream("myfile",true);
The above code will open the file in append mode so that the new content will be appended to the end of old content.
To know more about FileOutputStream constructors see this.

saving a file which contains dates results in keeping only last values

I am using the following code to store in a file some data.
(mydata is the data the user enters (double list) and dates_Strings is a string list where i store dates)
public void savefunc(){
SimpleDateFormat thedate = new SimpleDateFormat("dd/MM/yyyy",Locale.US);
Date d=new Date();
String formattedDate=thedate.format(d);
Log.d("tag","format"+formattedDate);
dates_Strings.add(formattedDate);
double thedata=Double.parseDouble(value.getText().toString().trim());
mydata.add(thedata);
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
directory.mkdirs();
File file = new File(directory, filename);
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for (int i=0;i<mydata.size();i++){
bw.write(mydata.get(i)+","+dates_Strings.get(i)+"\n");
}
value.setText("");
bw.flush();
bw.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
The problem is that if I enter some data in 06/05/13 and later some data in 07/05/13 , the file contains only the last data from the last date.I want to keep all the data.
Open the fileoutputstream in append mode
fos = new FileOutputStream(file, true);
Use fos = new FileOutputStream(file, true); to append data to the file instead of overwriting it.
FileOutputStream documentation

Categories

Resources