Java System 类详解 - in, out, err
几乎所有的都用过这个System类吧,因为大家学习的第一个语句大概就是
- package jdk.lang;
- public class SystemInspection {
- public static void main(String[] args) throws Exception {
- System.out.println(“Hello World”);
- }
- }
本文将一一详解这个类的标准输入(in),输出(out)和错误流(err)使用和原理。先看一个更复杂的例子:
- package jdk.lang;
- public class SystemIOE {
- public static void main(String[] args) throws Exception {
- 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));
- }
- }
在eclipse上运行,输出:
Hello Out
Hello Error
Hello In
Hello In
分析:
其实out, in 和 err是它的静态属性:
- public final static InputStream in = nullInputStream();
- public final static PrintStream out = nullPrintStream();
- public final static PrintStream err = nullPrintStream();
他们其实是在private static void initializeSystemClass()中初始化的:
- FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
- FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
- FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
- setIn0(new BufferedInputStream(fdIn));
- setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
- setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true));
FileDescriptor.out,FileDescriptor.in和FileDescriptor.err其实是
- public static final FileDescriptor in = standardStream(0);
- public static final FileDescriptor out = standardStream(1);
- public static final FileDescriptor err = standardStream(2);
再往下就是native的调用了。
同时System类还提供方法让你设置in,out和err,这样你就可以实现自己的日志系统了。运行下面的代码:
- package jdk.lang;
- 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 SystemIOE {
- 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(
- "c:/in.txt")));
- System.setIn(in);
- PrintStream out = new PrintStream(new FileOutputStream(new File(
- "c:/out.log")));
- System.setOut(out);
- PrintStream err = new PrintStream(new FileOutputStream(new File(
- "c:/err.log")));
- System.setErr(err);
- }
- }
转自:http://jackycheng2007.iteye.com/blog/1473625
欢迎访问:wenhao.ink