开发者

writing to a text file in java

开发者 https://www.devze.com 2023-04-11 07:47 出处:网络
I have the following function for writing to a file: public void writeToFile(String data) throws IOException {

I have the following function for writing to a file:

public void writeToFile(String data) throws IOException {
    FileWriter fstream = null;


    try {
        fstream = new FileWriter("out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(data);
        //Close the output stream
        out.close();
    } catch (IOException ex) {
        Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            fstream.close();
        } catch (IOException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

What it does every time it is开发者_运维问答 called it creates a new file and writes a new line. What I want to achieve is to check whether file exist. If not create a new file and write something, if exists then open the file and add a new line without erasing existing text. How to do that?


change your FileOutputStream constructor call to this:

fstream = new FileWriter("out.txt", true);


FileWriter takes in an additional parameter for appends, which specifies if you want to create a new file or append to an existing file

fstream = new FileWriter("out.txt", true);

http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File,%20boolean)


As there is a constructor in java's FileWriter class that can get an bool that idicates if the next "entry" is appended to the file, you should chage your

fstream = new FileWriter("out.txt");

to

fstream = new FileWriter("out.txt", true);

You can look up all those constructors in the java documentation: http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html

0

精彩评论

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