java 将一个文本文件中的内容复制到零一个文本文件中,用到IO流
程序员文章站
2024-03-04 15:36:29
...
package com.ggx.exercise;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import org.junit.Test;
public class copyText {
@Test
public void test() {
copyTextbyChar("e:\\in.txt", "e:\\out.txt");//调用方法(传递路径),灵活;
}
public void copyTextbyChar(String sourceName, String targetName) {
FileReader reader = null;
FileWriter writer = null;
try {
reader = new FileReader(sourceName);
writer = new FileWriter(targetName);
int len = -1;
while ( (len = reader.read()) != -1 ){//若读到-1,则说明文件读到了末尾;
writer.write(len); //逐个读取字符,然后逐个写入进targetName文件中;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (writer != null)
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
上一篇: java中一维数组的使用(初级)