316 复制Java文件打印流改进版
(myOtherStream)
【需求】
把"myOtherStream\\src\\e316\\66.txt",复制到 "myOtherStream\\src\\e316\\77.txt"
【思路】
(准备)(myOtherStream\\src\\e316\\66.txt)
(准备)(myOtherStream\\src\\e316\\662.txt)
- 根据 数据源 创建 字符输入流对象
- 根据 目的地 创建 字符输出流对象
- 读写 数据,复制文件
- 释放资源
---------------------------------------------
package e316;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Prepare {
public static void main(String[] args) throws IOException {
pre();
}
public static final void pre() throws IOException {
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("myOtherStream\\src\\e316\\66.txt"));
osw.write("take your place");
osw.close();
OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream("myOtherStream\\src\\e316\\662.txt"));
osw2.write("take your place\n\rtake your place ");
osw2.close();
}
}
---------------------------------------------
package e316;
import java.io.*;
public class CopyFileDemo extends Prepare {
public static void main(String[] args) throws IOException {
Prepare.pre();
BufferedReader br = new BufferedReader(new FileReader("myOtherStream\\src\\e316\\66.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("myOtherStream\\src\\e316\\77.txt"));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
//用1行语句实现以上3行代码,使用打印流的println方法
BufferedReader br2 = new BufferedReader(new FileReader("myOtherStream\\src\\e316\\662.txt"));
PrintWriter bw2 = new PrintWriter(new FileWriter("myOtherStream\\src\\e316\\772.txt"), true);
String line2;
while ((line2 = br2.readLine()) != null) {
bw2.println(line2);
}
br.close();
bw.close();
br2.close();
bw2.close();
}
}
---------------------------------------------
(66.txt)
take your place
take your place
(77.txt)
take your place
take your place
(662.txt)
take your place
take your place
(772.txt)
take your place
take your place