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工具,也许也是用类似的方法来实现的,哈哈。
阅读全文
0 0
- java IO笔记(System.int/out/error)
- Java IO: System.in, System.out, and System.error
- Java IO: System.in, System.out, System.err
- java.io中的System.in、 System.out和System.err
- Java学习笔记--System.out.println();
- Java IO操作——System类对IO的支持(System.out、System.err、System.in)
- Java IO流->处理流->标准输入输出流:System.in&System.out
- java System.out.println()
- Java: 省略System.out
- java学习笔记(一)System.out.println探究
- java io系列17之 System.out.println("hello world")原理
- java io系列17之 System.out.println("hello world")原理
- System.err与System.out区别(IO操作)
- java多线程System.out顺序
- java trick--system.out.println
- Java基础----System.in、System.out
- java基础(System.err和System.out)
- java --System.err和System.out
- ubuntu16.04 caffe2的安装
- USACO Section 1.3 Ski Course Design
- yii 时间插件的使用
- 修地球
- iconfont字体图标的使用
- java IO笔记(System.int/out/error)
- G
- 使用sonar质量代码走查工具需要注意的事项
- 数据结构api用法:
- WEB前端开发----JS
- 卷积层
- Session的理解
- 欢迎使用CSDN-markdown编辑器
- 自己玩彩票