栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java字符串写入文件更加有效的写法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java字符串写入文件更加有效的写法

 使用 try-with-resources 不用手动close;推荐FileWriter,代码更加简洁。

package util.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;

public class StrWriteFileUtil {

    
    public static void write(String str, String path) {

        try (FileWriter writer = new FileWriter(path)) {
            writer.write("");//清空原文件内容
            writer.write(str);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    
    public static void writeAppend(String str, String path) {

        try (FileWriter writer = new FileWriter(path, true)) {
            writer.write(str);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    
    public static void outputStreamWrite(String str, String path) {

        File txt = new File(path);
        try (FileOutputStream fos = new FileOutputStream(txt)) {
            if (!txt.exists()) {
                txt.createNewFile();
            }
            byte[] bytes = str.getBytes();
            int b = bytes.length;   //是字节的长度,不是字符串的长度
            fos.write(bytes, 0, b);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    
    public static void outputStreamWriteAppend(String str, String path) {

        File txt = new File(path);
        try (FileOutputStream fos = new FileOutputStream(txt, true)) {
            if (!txt.exists()) {
                txt.createNewFile();
            }
            byte[] bytes = str.getBytes();
            int b = bytes.length;   //是字节的长度,不是字符串的长度
            fos.write(bytes, 0, b);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    public static void main(String[] args) {
        String str = "hello world!";
        String path = "./test/3.txt";
        //write(str,path);
        //writeAppend(str,path);
        // outputStreamWrite(str, path);
        outputStreamWriteAppend(str, path);

    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/973006.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号