您的位置:首页 > 编程语言 > Java开发

java的标准输入/输出流

2017-04-19 20:22 288 查看
原文转自:http://blog.csdn.net/jack_jyh/article/details/52388271

大体了解了一些java中标准流变量和方法

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);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

结果 

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐