I Have a code for writing into a file each time there is an entry into the textfield. but after the process, when an开发者_高级运维 entry is made again the file is rewritten instead of continuing with the entries to the file, and so I lose the previous data. How do I rewrite to the existing one, so that later I get to read those data even after closing the app.
The code for the write process is given :
public boolean writeToFile(String dataLine) {
dataLine = "\n" + dataLine;
try {
File outFile = new File(filepath);
dos = new DataOutputStream(new FileOutputStream(outFile));
dos.writeBytes(dataLine);
dos.close();
} catch (FileNotFoundException ex) {
return (false);
} catch (IOException ex) {
return (false);
}
return (true);
}
Could anyone pls make changes to the code as necessary and post it to me.
The [Java API for FileOutputStream][1] states:
public FileOutputStream(String name,
boolean append)
throws FileNotFoundException)
Creates an output file stream to write to the file with the specified name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection.
So, your code should look like this:
public boolean writeToFile(String dataLine) {
dataLine = "\n" + dataLine;
try {
File outFile = new File(filepath);
dos = new DataOutputStream(new FileOutputStream(outFile,true));
dos.writeBytes(dataLine);
dos.close();
} catch (FileNotFoundException ex) {
return (false);
} catch (IOException ex) {
return (false);
}
return (true);
}
[1]: http://download.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.lang.String, boolean)
Use the constructor FileOutputStream(File file, boolean append)
with append = true
Open file in append
mode.
make it
dos = new DataOutputStream(new FileOutputStream(outFile),true);
- Document
See [http://download.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File, boolean)][1]
Also note that you should probably use a FileWriter to write text. FileOutputStream is for binary data.
[1]: http://download.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File, boolean)
精彩评论