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

来源:互联网 发布:雪梨的淘宝店叫什么名 编辑:程序博客网 时间:2024/06/05 02:15

在前面的篇幅中我们有用到过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工具,也许也是用类似的方法来实现的,哈哈。