下面的代码我们先了解一下PrintStream流
import java.io.PrintStream;
/*标准输出流*/
/*标准字节输出流,默认输出到控制台*/
public class PrintStreamTest {
public static void main(String[] args) {
//联合写
System.out.println("hello word");
// 分开写
PrintStream ps = System.out;
ps.println("hello word");
}
}
public class PrintStreamTest {
public static void main(String[] args) {
/* System.out.println("hello word");
PrintStream ps = System.out;
ps.println("hello word");*/
try {
/*字节输出流*/
FileOutputStream fos = new FileOutputStream("E:\\IDEA\\Java\\StudentTwo\\src\\IOTest\\log.txt");
PrintStream printStream = new PrintStream(fos);
/*标准输出流不再指向控制台,而是指向log文件*/
System.setOut(printStream);
System.out.println("hello word");
System.out.println("我是一个大帅哥");
/*仍需要刷新*/
printStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
/* 这个流不需要我们关闭,因为它会自己关闭*/
}
}
运行程序之后,结果并没有在控制台显示,而是在log文件中显示
为了加深使用,我们再来写一个,将日期输出在log文件之中
代码如下所示
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PrintStreamTest02 {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("\\E:\\IDEA\\Java\\StudentTwo\\src\\IOTest\\log.txt");
PrintStream printStream = new PrintStream(fos);
System.setOut(printStream);
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String time = sdf.format(date);
System.out.println(time);
printStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
结果: