java IO笔记(System.int/out/error)

25 篇文章 0 订阅

在前面的篇幅中我们有用到过System.int,System.out,那么它们是怎么工作的呢,本篇将来简单的说说它们。

从源码中看出System.in,System.out,System.err都是System类中的静态属性,如图所示:


可以看出System.in是一个InputStream,System.out和System.err是一个PrintStream。当jvm初始化时,自动执行initializeSystemClass方法时,会自动为3个标准流进行初始化。

java还为我们提供了3个流对应的set方法,可以重定向流,从而方便我们记录一些系统日志,下面将举一个简单的小例子来实现自定义的日志系统:

package systemIO;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;

public class SystemIOtest {
	 public static void main(String[] args) throws Exception {  
	        redirect();  
	        helloIO();  
	    }  
	  
	    private static void helloIO() throws IOException {  
	        System.out.println("Hello Out");  
	        System.err.println("Hello Error");  
	        byte[] b = new byte[1024];  
	        int count = System.in.read(b);  
	        System.out.println(new String(b, 0, count));  
	    }  
	  
	    public static void redirect() throws FileNotFoundException {  
	        InputStream in = new BufferedInputStream(new FileInputStream(new File("./src/file/test.txt")));  
	        System.setIn(in);  
	        PrintStream out = new PrintStream(new FileOutputStream(new File(  
	                "./src/file/out.log")));  
	        System.setOut(out);  
	        PrintStream err = new PrintStream(new FileOutputStream(new File(  
	                "./src/file/error.log")));  
	        System.setErr(err);  
	    }  
}
运行上述程序后,我们看见在对应的目录出生成了对应的log文件,如图所示:


打开文件,可以看到如下内容:



这让我想起了一些log工具,也许也是用类似的方法来实现的,哈哈。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

moonfish0607

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值