java.io.printStream
标准的字节输出流。默认输出到控制台
public static void main(String[] args) throws Exception {
//联合起来写
System.out.println("hello world");
//分开写
PrintStream ps = System.out;
ps.println("hello zhangsan");
ps.println("hello lisi");
ps.println("hello wangwu");
//标准输出流不需要捕获异常 不需要手动close()关闭
/*
之前学习过的方法和属性
System.gc()
System.currentTimeMills();
PrintStream ps = System.out;
System.exit();
System.arraycopy()
*/
//改变标准输出流的输出方向
//标准输出流不再指向控制台,指向log文件
PrintStream printStream = new PrintStream(new FileOutputStream("log.txt"));
//修改输出方向,将输出方向修改到log文件
System.setOut(printStream);
// 再输出
System.out.println("hello world");
System.out.println("hello kitty");
System.out.println("hello zhangsan");
}
日志文件
public class Logger {
public static void log(String msg){
try {
PrintStream printStream = new PrintStream(new FileOutputStream(
"log.txt",true));
System.setOut(printStream);
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String format = sdf.format(date);
System.out.println(format + ":" + msg);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
public class LogApplication {
public static void main(String[] args) {
Logger.log("调用了System.gc()方法");
Logger.log("不想打代码");
Logger.log("烦死了");
}
}