再理解System.out输出、System.in输入

    技术2026-01-10  13

    文章目录

    System的三个支持IO的常量out常量对象测试err常量对象测试in常量对象的测试 System设置三个常量的输入输出重定向重定向方法 最初我理解的System.out.println()就是系统输出,System.in就是系统键盘输入,今天学习了System对JavaIO的支持,恍然大悟~ 先说结论:

    System.out 是 PrintStream的对象,表示通过显示器输出,可以使用PrintStream对象中的任何方法。System.err 也是 PrintStream的对象,也可以使用PrintStream对象中的任意方法,但是使用此常量对象输出的信息是不希望被程序用户所看到的。System.in 是InputStream的对象,可以通过键盘向程序中输出信息。

    如果有小伙伴们依然不懂,请往下看

    System的三个支持IO的常量

    序号System类中的常量描述1public static final PrintStream out对应系统的标准输出,一般为显示器2public static final PrintStream err错误信息输出3public static final InputStream in对应着标准输入,一般是键盘

    看到这里会不会有些小伙伴猛然地恍然大悟,原来我们在程序中的输入输出也是采用了JavaIO了啊,确实是的

    out常量对象测试
    package chapter_twelve; import com.sun.jndi.ldap.sasl.LdapSasl; import java.io.OutputStream; import java.io.PrintStream; public class SystemDemo01 { public static void main(String[] args) throws Exception{ //System.out为PrintStream类对象 OutputStream outputStream = System.out; //此时的字节输出流是向屏幕上进行输出 outputStream.write("Hello World!!!".getBytes()); //将字符串转换为byte字节进行输出 outputStream.close(); //关闭输出流 } }

    运行结果

    Hello World!!!
    err常量对象测试
    package chapter_twelve; import java.io.IOException; import java.io.OutputStream; public class SystemDemo02 { public static void main(String[] args) { /*OutputStream outputStream = System.err;*/ String string = "Hello World!!!"; //声明一个非数字的字符串 try{ Integer.parseInt(string); //利用Integer类进行强制类型转换 }catch (Exception e){ System.err.println(e); //输出打印错误信息 } } }

    运行结果(红色字体的输出)

    java.lang.NumberFormatException: For input string: "Hello World!!!"
    in常量对象的测试
    package chapter_twelve; import java.io.InputStream; public class SystemDemo03 { public static void main(String[] args) throws Exception{ //向外抛出所有的异常 InputStream inputStream = System.in; //InputStream接收子类对象,设置输入信息为标准键盘输入 byte[] bytes = new byte[1024]; //定义存放数据的字节数组,由于采用此种方式输入,数据长度不确定 System.out.println("请输入具体的信息:"); int len = inputStream.read(bytes); //通过键盘输入数据,将输入的数据存放到字节数组中,并返回读入数据长度 System.out.println("您输入的信息为:"); System.out.print(new String(bytes,0,len)); //输出用户输入的数据 } }

    运行结果

    请输入具体的信息: Hello World! 您输入的信息为: Hello World!

    System设置三个常量的输入输出重定向

    System类也可以对out、err、in三个常量对象进行重定向输入输出位置。

    重定向方法
    序号方法类型描述1public static void setOut(PrintStream out)普通重定向"标准"输出流2public static void setErr(PrintStream out)普通重定向"标准"错误输出流3public static void setIn(InputStream in)普通重定向"标准"输入流

    重定向使用较为简单,再次就不再阐述了哦,嘿嘿,有兴趣的小伙伴可以多测试测试~

    一般情况下在程序项目的开发中,不建议使用System常量的重定向方法,以免损失程序的合理性,哈哈

    Processed: 0.027, SQL: 9