文章目录
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
{
OutputStream outputStream
= System
.out
;
outputStream
.write("Hello World!!!".getBytes());
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
) {
String string
= "Hello World!!!";
try{
Integer
.parseInt(string
);
}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
;
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常量的重定向方法,以免损失程序的合理性,哈哈