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

2022-06-26 10:55:22

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)

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

  • 作者:袁保健
  • 原文链接:https://blog.csdn.net/qq_32048015/article/details/99617760
    更新时间:2022-06-26 10:55:22