append text to the end of the file - android

I am using the below code segment to write text to the end o the file for each time it is called. But, it is erasing the old data and then writes the new data to the beginning of the file. How can I fix the below code so that it is append new data always end of the file ?
public boolean writeToFile(String directory, String filename, String data ){
File out;
OutputStreamWriter outStreamWriter = null;
FileOutputStream outStream = null;
out = new File(new File(directory), filename);
if ( out.exists() == false ){
out.createNewFile();
}
outStream = new FileOutputStream(out) ;
outStreamWriter = new OutputStreamWriter(outStream);
outStreamWriter.append(data);
outStreamWriter.flush();
}

Try to set append boolean value to true in FileOutputStream:
outStream = new FileOutputStream(out, true);
outStreamWriter = new OutputStreamWriter(outStream);

Related

While reading data from a stream, why does my program hang?

While reading data from a stream I am writing to a newly created temporary XML file. But the program hangs.
What have I missed here?
if (deviceSocket.isConnected()) {
OutputStream os = deviceSocket.getOutputStream();
os.write(xmlStr.getBytes());
os.flush();
// Read Response from Socket
respFromDevice = new BufferedReader(new InputStreamReader(deviceSocket.getInputStream()));
FileWriter fileWriter = null;
// Write into temp xml file
String response;
while ((response = respFromDevice.readLine()) != null) {
sb.append(response);
File newTextFile = new File("tmp.xml");
fileWriter = new FileWriter(newTextFile);
fileWriter.write(sb.toString());
//Files.write(Paths.get("temp.xml"), sb.toString().getBytes());
System.out.println(response);
}
}

Merge two mp3 file in android

I want merge multiple mp3 file in android but for example I just do this with two file :
FileInputStream fileInputStream = new FileInputStream(soundFile.getAbsolutePath() + 0);
FileInputStream fileInputStream1 = new FileInputStream(soundFile.getAbsolutePath() + 1);
SequenceInputStream sequenceInputStream = new SequenceInputStream(fileInputStream, fileInputStream1);
FileOutputStream fileOutputStream = new FileOutputStream(soundFile.getAbsolutePath());
int temp;
while ((temp = sequenceInputStream.read()) != -1) {
fileOutputStream.write(temp);
}
fileInputStream.close();
fileInputStream1.close();
sequenceInputStream.close();
fileOutputStream.close();
I recorded two sound with "ttt.mp30" and "ttt.mp31" file. then I want to merge it to "ttt.mp3"
but when I use this code for merge, it just create the ttt.mp3 witch play ttt.mp30 but it doesn't play ttt.mp31 file
whats the problem ?
thanks
EDIT :
if I use :
SequenceInputStream sequenceInputStream = new SequenceInputStream(fileInputStream1, fileInputStream);
insted of :
SequenceInputStream sequenceInputStream = new SequenceInputStream(fileInputStream, fileInputStream1);
the ttt.mp3 just play ttt.mp31 file
Edit :
the record option :
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
import java.io.*;
public class TwoFiles
{
public static void main(String args[]) throws IOException
{
FileInputStream fistream1 = new FileInputStream("path\\1.mp3"); // first source file
FileInputStream fistream2 = new FileInputStream("path\\2.mp3");//second source file
SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
FileOutputStream fostream = new FileOutputStream("path\\final.mp3");//destinationfile
int temp;
while( ( temp = sistream.read() ) != -1)
{
// System.out.print( (char) temp ); // to print at DOS prompt
fostream.write(temp); // to write to file
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
}

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