3 回答
TA贡献1772条经验 获得超6个赞
无需编写任何代码,只需在控制台上的cmd中编写即可:
javac myFile.java
java ClassName > a.txt
输出数据存储在a.txt文件中。
TA贡献1946条经验 获得超4个赞
要保留控制台输出,即写入文件并将其显示在控制台上,您可以使用如下类:
public class TeePrintStream extends PrintStream {
private final PrintStream second;
public TeePrintStream(OutputStream main, PrintStream second) {
super(main);
this.second = second;
}
/**
* Closes the main stream.
* The second stream is just flushed but <b>not</b> closed.
* @see java.io.PrintStream#close()
*/
@Override
public void close() {
// just for documentation
super.close();
}
@Override
public void flush() {
super.flush();
second.flush();
}
@Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);
second.write(buf, off, len);
}
@Override
public void write(int b) {
super.write(b);
second.write(b);
}
@Override
public void write(byte[] b) throws IOException {
super.write(b);
second.write(b);
}
}
并用于:
FileOutputStream file = new FileOutputStream("test.txt");
TeePrintStream tee = new TeePrintStream(file, System.out);
System.setOut(tee);
(只是一个想法,不完整)
添加回答
举报