前言
IO流—PrintStream标准字节输出流
PrintStream标准字节输出流
1.PrintStream标准字节输出流:
注意:PrintStream标准字节输出流不需要手动close()关闭。
* 默认输出到控制台中
2.PrintStream实例:
LogUtil 代码如下:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LogUtil {
public static void log(String agr){
FileOutputStream fos = null;
PrintStream ps = null;
try {
fos = new FileOutputStream("log");
ps = new PrintStream(fos);
//改变输出方向
System.setOut(ps);
//获取当前时间
Date nowTime = new Date();
//格式化时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String strTime = sdf.format(nowTime);
System.out.println(strTime + ":" + agr);
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Logger 代码如下:
public class Logger {
public static void main(String[] agrs){
LogUtil.log("第一次使用");
}
}