Java: Append content to text file

foreword

At work, the content of an existing file is often appended. Here is a simple example program.

1. The program is relatively simple, paste the code directly

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class CreateFile {

    public static void main(String[] args) {

        String saveFile = "test.json";
        File file = new File(saveFile);
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;

        try {
            if (!file.exists()) {
                boolean hasFile = file.createNewFile();
                if(hasFile){
                    System.out.println("file not exists, create new file");
                }
                fos = new FileOutputStream(file);
            } else {
                System.out.println("file exists");
                fos = new FileOutputStream(file, true);
            }

            osw = new OutputStreamWriter(fos, "utf-8");
            osw.write("测试内容"); //写入内容
            osw.write("
");  //换行
        } catch (Exception e) {
            e.printStackTrace();
        }finally {   //关闭流
            try {
                if (osw != null) {
                    osw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2. Program running results

Running the program for the first time
prints:
first run result

document:
Contents of newly created file

Second run: the
program prints:
Results of the second run

document:
file append

3. Conclusion:
Be sure to remember to close the stream, otherwise the file will be created, but there is no content.

Guess you like

Origin blog.csdn.net/m0_54853503/article/details/123952087