简体   繁体   中英

writing to a text file in java

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?

将FileOutputStream构造函数调用更改为:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM