题目:
将C盘的一个文本文件复制到E盘
思路一:
1,读取一个已有的文本文件,使用字符读取流和文件相关联
2,创建一个目的,用于存储读到数据
3,频繁的读写操作
4,关闭流资源
代码示例一:
public class CopyTextTest {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//1,读取一个已有的文本文件,使用字符读取流和文件相关联。
FileReader fr = new FileReader("C:\\Demo.txt");
//2,创建一个目的,用于存储读到数据。
FileWriter fw = new FileWriter("E:\\copytext_1.txt");
//3,频繁的读写操作。
int ch = 0;
while((ch=fr.read())!=-1){
fw.write(ch);
}
//4,关闭流资源。
fw.close();
fr.close();
}
}
思路二:
1,创建一个临时容器,用于缓存读取到的字符。
2,定义一个变量记录读取到的字符数,(其实就是往数组里装的字符个数 )
代码示例二:
public class CopyTextTest_2 {
private static final int BUFFER_SIZE = 1024;
/**
* @param args
*/
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("C:\\Demo.txt");
fw = new FileWriter("E:\\copytest_2.txt");
//创建一个临时容器,用于缓存读取到的字符。
char[] buf = new char[BUFFER_SIZE];//这就是缓冲区。
//定义一个变量记录读取到的字符数,(其实就是往数组里装的字符个数 )
int len = 0;
while((len=fr.read(buf))!=-1){
fw.write(buf, 0, len);
}
} catch (Exception e) {
// System.out.println("读写失败");
throw new RuntimeException("读写失败");
}finally{
if(fw!=null)
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
if(fr!=null)
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
思路三:BufferReader&BufferWriter
public class CopyTextByBufTest {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("C:\\Demo.txt");
BufferedReader bufr = new BufferedReader(fr);
FileWriter fw = new FileWriter("E:\\buf_copy.txt");
BufferedWriter bufw = new BufferedWriter(fw);
String line = null;
while((line=bufr.readLine())!=null){
bufw.write(line);
bufw.newLine();
bufw.flush();
}
bufw.close();
bufr.close();
}
}