Java中的文件复制相较Python而言,涉及到输入输出流的概念,实现中会调用很多对象,复杂很多,在此以文件复制进行简单总结。
这里是一个简单的处理代码:
import java.io.*;
public class Demo {
public static void main(String[] args) throws IOException{
// 输入文本定位
BufferedInputStream in = new BufferedInputStream(
new FileInputStream("in.txt"));
// 输出文本定位
PrintStream out = new PrintStream(new BufferedOutputStream(
new FileOutputStream("out.txt")));
/* 重定向 */
System.setIn(in); // 由原来从键盘作为输入重定向到文本 'in.txt'
System.setOut(out); // 由原来从键盘作为输入重定向到文本 'out.txt'
System.setErr(out); // 同上
BufferedReader br = new BufferedReader( // Buffer流使进程效率更高
new InputStreamReader(System.in)); // 此处的节点流 InputStreamReader 处理数据
String s;
while ((s = br.readLine()) != null) {
System.out.println(s);
}
in.close();
out.close();
}
}
这里有个需要理解的地方就是输入输出重定向的问题:
原来 System.in 所定向的是键盘,而 System.out 所定向的是显示器,由
System.setIn(in);
System.setOut(out);
System.setErr(out);
而将输入重定向到了文件 in.txt ,将输出重定向到了 out.txt ,所以在 while 中,System.out.printf() 自然也就将 String 输出到了文件 out.txt 中。