How to add a string to end of a .txt file? [duplicate]
开发者_JAVA技巧Possible Duplicate:
How to append text to an existing file in Java
How can I add a string to the end of a .txt file?
From here
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("checkbook.txt", true));
bw.write("400:08311998:Inprise Corporation:249.95");
bw.newLine();
bw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally { // always close the file
if (bw != null) {
try {
bw.close();
} catch (IOException ioe2) {
// just ignore it
}
}
}
As advised by Joachim Sauer, instead of using FileWriter
, you can use
new OutputStreamWriter(new FileOutputStream(..), ecnoding)
if you want to specify the encoding of the file. FileWriter
uses the default encoding, which changes from installation to installation.
English term to look for: "append"
You need to perform the following steps:
- open the file.
- append the string.
- close the file.
Read about the FileOutputStream class.
精彩评论