开发者

How to add a string to end of a .txt file? [duplicate]

This question already has answers here: Closed 11 years ago.
开发者_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:

  1. open the file.
  2. append the string.
  3. close the file.

Read about the FileOutputStream class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜