为什么一下两段代码效果一样,哪位高手给解释一下
String filename="C://Users//Administrator//Desktop//极速传输//1.script";
File file=new File(filename);
try {
PrintStream printStream = new PrintStream(file);
System.setOut(printStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String filename="C://Users//Administrator//Desktop//极速传输//1.script";
File file=new File(filename);
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(file);
PrintStream printStream = new PrintStream(fileOutputStream);
System.setOut(printStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
------解决方案--------------------
效果一样,但实现的方式和效率不一样,一个是用打印流传输文件,一个是用文件输出流传输文件。
------解决方案--------------------
看源代码就知道。
最终差别就在boolean autoFlush 第一true 第二false
private PrintStream(boolean autoFlush, OutputStream out) {
super(out);
this.autoFlush = autoFlush;
this.charOut = new OutputStreamWriter(this);
this.textOut = new BufferedWriter(charOut);
}
------解决方案--------------------
public PrintStream(File file) throws FileNotFoundException {
this(false, new FileOutputStream(file));
}
public PrintStream(OutputStream out) {
this(out, false);
}
public PrintStream(OutputStream out, boolean autoFlush) {
this(autoFlush, requireNonNull(out, "Null output stream"));
}
private PrintStream(boolean autoFlush, OutputStream out) {
super(out);
this.autoFlush = autoFlush;
this.charOut = new OutputStreamWriter(this);
this.textOut = new BufferedWriter(charOut);
}
两者确实一样,因为你传file进去,它内部也会创建一个FileOutputStream