使用java的输出流写一个json格式的文件在指定目录下

思路是这样的,先写一个工具类的静态方法,该方法将传来的json字符串写成一个文件。然后在写一个线程类,通过构造方法传参,将json字符串传进来。我把测试类、写文件类、线程类的代码贴出来,大家一看就明白了我的思路。

写文件的类:

package com.bdc.utils;


import java.io.*;

/**
 * Created by Jony lai on 2017/5/17.
 */
public class WriteJsonFile {
    public static void WriteConfigJson(String args) {
        String src = ConstantUtil.WRITE_JSON_FILE_SRC;//这里需要定义一个变量,如"E:\\json\\conf.json";//把json文件写到这个目录下

        File file = new File(src);

        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            file.delete();
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            FileWriter fw = new FileWriter(file, true);
            fw.write(args);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
 线程类:

package com.bdc.utils;

/**
 * Created by jony lai on 2017/5/17.
 */
public class WriteFileThread extends Thread{

    String StingJson = "";//定义线程内变量
    public WriteFileThread(String StingJson){//定义带参数的构造函数,达到初始化线程内变量的值
        this.StingJson = StingJson;
    }
    @Override
    public void run() {
        WriteJsonFile.WriteConfigJson(StingJson);
    }
}
测试类:

package com.bdc;

import com.bdc.utils.WriteFileThread;

/**
 * Created by jony lai on 2017/5/17.
 */
public class TestWriteConfigJson {
    public static void  main(String[] args){
        WriteFileThread writeFileThread = new WriteFileThread("{\"name\": \"Jony\",\"description\": \"你好\",\"open source\": {\"是否开源\": true,\"GitHub\": \"赖全强\"}}");
        writeFileThread.start();


    }
}


你可能感兴趣的:(使用java的输出流写一个json格式的文件在指定目录下)