Java(标准输入/输出流)

来源:互联网 发布:淘宝卖家被敲诈 编辑:程序博客网 时间:2024/05/16 05:48

Java通过系统类System实现标准输入/输出的功能,定义了3个流变量:in,out,和err.这3个流在Java中都定义为静态变量,可以直接通过System类进行调用。System.in表示标准输入,通常指从键盘输入数据;System.out表示标准输出,通常指把数据输出到控制台或者屏幕;System.err表示标准错误输出,通常指把数据输出到控制台或者屏幕。

1.简单标准输入
System.in作为字节输入流类InputStream的对象实现标准输入,通过read()方法从键盘接受数据。
int read()
int read(byte b[])
int read(byte b[],int offset,int len)

import java.io.IOException;public class StdInput{    public static void main(String[] args) throws IOException     {        System.out.println("input:");        byte b[]=new byte[512];        int count=System.in.read(b);        System.out.println("Output");        for(int i=0;i<count;i++)        {            System.out.print(b[i]+" ");        }        System.out.println();        for(int i=0;i<count;i++)        {            System.out.print((byte)b[i]+" ");        }        System.out.println("count="+count);    }}

结果
input:
abcd
Output
97 98 99 100 13 10
97 98 99 100 13 10 count=6

分析:程序运行使,从键盘输入4个字符abcd并按Enter键,保存在缓冲区b中的元素个数count为6,Enter占用最后两个字节

2.Scanner类与标准输入结合
在通常情况下需要从标准输入读取字符,整数,浮点数等具体类型的数据。System.in作为标准输入流,是InputStream类的一个对象,其read()方法的主要功能是读取字节和字节数组,不能直接得到需要的数据(如整型,浮点型)。此时,需要另外一个类java.util.Scanner的配合。可以利用Scanner类对标准输入流System.in的数据进行解析,得到需要的数据。

3.标准输出
System.out作为打印流PrintStream的对象实现标准输出,其定义了print和println方法,支持将Java的任意基本类型作为参数。
public void print(int i);
public void println(int i);
JDK5.0后的版本对PrintStream类进行了扩充,支持数据的格式化输出,增加了printf()方法。
public PrintStream printf(String format,Object…args)
public PrintStream printf(Locale 1,String format,Object…args)

0 0
原创粉丝点击