Java IO

Java IO,第1张

  • 字符流针对纯文本文件,注意doc文件不是纯文本文件。
  • FileWriter(File file) 如果被写文件存在,写数据会覆盖原内容
  • FileWriter(File file, boolean append) append=true,会在原内容后面追加新写的内容
1 每次读取一个字符
@Test
@DisplayName("每次读取一个字符")
public void testFileReader() {
    String filePath = "src/main/resources/json/student_array.json";
    String fileCopyPath = "src/main/resources/json/student_array_copy.json";
    try (FileReader fileReader = new FileReader(filePath);
         FileWriter fileWriter = new FileWriter(fileCopyPath)
    ) {
        int data;
        while ((data = fileReader.read()) != -1) {
            fileWriter.write(data);
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
2 每次读取字符数组
@Test
@DisplayName("每次读取字符数组")
public void testFileReaderArray() {
    String filePath = "src/main/resources/json/student_array.json";
    String fileCopyPath = "src/main/resources/json/student_array_copy_array.json";
    try (FileReader fileReader = new FileReader(filePath);
         FileWriter fileWriter = new FileWriter(fileCopyPath)
    ) {
        int readLength = 0;
        char[] chars = new char[1024];
        while ((readLength = fileReader.read(chars)) != -1) {
            fileWriter.write(chars, 0 ,readLength);
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/790957.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-05
下一篇 2022-05-05

发表评论

登录后才能评论

评论列表(0条)

保存