java: write text content to file

Table of contents

the code

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        // 说明:我的目的是将参数2中的文本写入到参数1中的文件中,并且该参数1中的json文件不存在
        writeText2File("C:\\test\\20220301\\hello.json", "{
    
    \"code\":200,\"message\":\"成功\",\"success\":true}");
    }

    /**
     * 将文本写入文件
     *
     * @param filePath 文件全路径
     * @param text     文本
     **/
    public static void writeText2File(String filePath, String text) {
    
    
        // 创建文件
        File file = new File(filePath);
        if (!file.exists()) {
    
    
            try {
    
    
                // 创建文件父级目录
                File parentFile = file.getParentFile();
                if (!parentFile.exists()) {
    
    
                    parentFile.mkdirs();
                }
                // 创建文件
                file.createNewFile();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }

        // 将文本写入文件
        writeText2File(file, text);
    }

    /**
     * 将文本写入文件
     *
     * @param file 文件对象
     * @param text 文本
     **/
    public static void writeText2File(File file, String text) {
    
    
        FileWriter writer = null;
        try {
    
    
            writer = new FileWriter(file);
            char[] chars = text.toCharArray();
            writer.write(chars);
            writer.flush();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (writer != null) {
    
    
                try {
    
    
                    writer.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }
}

result

insert image description here

Guess you like

Origin blog.csdn.net/qq_42449963/article/details/129277333