- 字符流针对纯文本文件,注意doc文件不是纯文本文件。
- FileWriter(File file) 如果被写文件存在,写数据会覆盖原内容
- FileWriter(File file, boolean append) append=true,会在原内容后面追加新写的内容
@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);
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)