(写文件)将字符串保存成文件

来源:互联网 发布:打开网页下载php文件 编辑:程序博客网 时间:2024/06/04 20:12
java中将字符串写成文件保存到电脑的指定位置,该文件形式可以根据自己所需进行指定,例如.json 、.txt等。
    public void writeFile(String content, String FilePath) {        try {            // String data = " This content will append to the end of the file";            File file = new File(FilePath);            // if file doesnt exists, then create it            if (!file.exists()) {                file.createNewFile();            } else {                file.delete();                file.createNewFile();            }            // true = append file            FileWriter fileWritter = new FileWriter(file, false);//file是要写入数据的File对象            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);            bufferWritter.write(content);            bufferWritter.close();          } catch (IOException e) {            e.printStackTrace();        }    }
需要注意的是,一般我们写文件都是每次更新,而不是在上次的基础上续写,因此boolean变量置为false。
0 0