package io;
import org.junit.Test;
import java.io.*;
/**
* @author 苗晓强
* @date 2023/8/4 22:58
* 读取文件输出到另一个文件
*/
public class FileReaderWriterTest {
@Test
public void test(){
FileReader fileReader = null;
FileWriter fileWriter = null;
//确保流一定被关闭,采用 try/catch/finally语句块
try {
//根据文件路径获取要读取的文件
File srcfile = new File("src/io/hello.txt");
//目标文件
File destFile = new File("info.txt");
fileReader = new FileReader(srcfile);
fileWriter = new FileWriter(destFile);
//Reads characters into an array.
char[] buffer = new char[1024];
int len;
//The number of characters read, or -1 if the end of the stream has been reached
while ((len = fileReader.read(buffer)) != -1){
fileWriter.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
//防止文件未找到(FileNotFoundException),调用close方法,会出现空指针异常
if (fileReader != null){
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fileWriter != null){
fileWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
IO流-复制文件
最新推荐文章于 2024-01-08 22:26:03 发布