java 读取写入文本文件(.txt .json等)文件内容

1.目的

读取文本内容到字符串, 然后修改

有时候需要修改一些文本内容, 这时候就需要读取修改了了

1.使用FileInputStream

先创建File对象

再用FileInputStream

 private static String readString3(String fileSrc) {
        String str  = "";
        File   file = new File(fileSrc);
        try {
            FileInputStream in = new FileInputStream(file);
            // size  为字串的长度 ,这里一次性读完
            int    size   = in.available();
            byte[] buffer = new byte[size];
            in.read(buffer);
            in.close();
            str = new String(buffer, "GB2312");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            return null;
        }
        return str;
    }

函数解析

1. File函数

通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例

给本地地址----获得File实例

 

2.FileInputStream 

 

 

 

2.使用FileReader  读取

无须使用File类, 直接加载地址就行

    public static String  FileReaderDemo(String filePath) throws IOException {
        FileReader fr=new FileReader(filePath);
        int i;
        String str="";
        while((i=fr.read())!=-1)
            str=str+ (char)i;
        fr.close();
        return str;
    }

 

2.1使用BufferedReader

BufferedReader (Reader in , int size)

参数是一个Reader  类型  (或者是其子类)

创建一个缓冲字符输入流  (默认或指定大小), 这个能一行一行读取

 public static String readJsonFile(String path){
        String laststrJson = "";
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader(new File(path)));
            String tempString = null;
            int line = 1;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                laststrJson = laststrJson + tempString;
                line++;
            }
            reader.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return laststrJson;
    }

 

 

 

3.使用FileWriter  写入

 public static void FileWriterDemo(String content){
        try(
            FileWriter fileWriter = new FileWriter("C:\\Users\\yuanbaojian\\Desktop\\new.txt")) {
            fileWriter.append(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

1.FileWriter

FileWriter(File file, boolean append)

如果两个参数, 第二个是添加模式

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值