Java IO 之System类及其它

System类管理标准输入输出流和错误流

一、使用System.out作为输出流

 

package cn.sisy.io;
import java.io.*;
public class SystemDemo01 {
	public static void main(String[] args)throws Exception {
		//抽象类通过子类实现不同的功能
		OutputStream out = null;
		// System.out是PrintStream,是OutputStream子类
		//谁为我的抽象类实例化,那么我的输出就是向着谁的
		out = System.out;
		// 现在的out对象具备了向屏幕上打印内容的能力
		String str = "Hello,World" ;
		out.write(str.getBytes()) ;
		out.close() ;
	}
}

 二、使用PrintWriter结合System.out提升打印能力

打印流包括PrintStream和PrintWriter

 

package cn.sisy.io;
import java.io.*;
public class SystemDemo02 {
	public static void main(String[] args)throws Exception {
		
		PrintWriter out = new PrintWriter(System.out) ;
		// 具备了向文件中打印数据的能力
		//打印的能力得到了增强
		out.println(true) ;
		out.println(30) ;
		out.println("Hello,World") ;
		out.close() ;
		
	}
}

 true

30

Hello,World

三、使用键盘输入流System.in

 

package cn.sisy.io;
import java.io.*;
public class SystemDemo03 {
	public static void main(String[] args)throws Exception {
		
		InputStream in = null ;
		// 数据等待键盘的输入
		in = System.in ;
		byte b[] = new byte[1024] ;
		// 读的时候是等待用户的输入
		int len = in.read(b) ;
		in.close() ;
		System.out.println("输入的内容为:"+new String(b,0,len)) ;
		
	}
}

 

 

a b c d

输入的内容为:a b c d

四、BufferedReader以及转换流InputStreamReader和OutputStreamReader

思考上面的程序容易发现,键盘输入的大小事收数组大小限制的,这样可能会导致中文乱码的情况产生。(*一个中文是两个字节)

当然程序可以通过改成从键盘一直读数据的方式来解决大小限制的问题,但我们下面介绍一种更加好的方式。

BufferedReader:从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。 

可以指定缓冲区的大小,或者可使用默认的大小。大多数情况下,默认值就足够大了。 

通常,Reader 所作的每个读取请求都会导致对底层字符或字节流进行相应的读取请求。因此,建议用 BufferedReader 包装所有其 read() 操作可能开销很高的 Reader(如 FileReader 和 InputStreamReader)。例如, 

 BufferedReader in= new BufferedReader(new FileReader("foo.in"));

 将缓冲指定文件的输入。如果没有缓冲,则每次调用 read() 或 readLine() 都会导致从文件中读取字节,并将其转换为字符后返回,而这是极其低效的。 

通过用合适的 BufferedReader 替代每个 DataInputStream,可以对将DataInputStream 用于文字输入的程序进行本地化。

 

InputStreamReader和OutputStreamReader:前者将输入字节流转换成字符流, 后者将输出字符流转换成字节流。

 

import java.io.* ;
public class SystemDemo04{
	public static void main(String args[]){

		BufferedReader buf = null ;
		// 此处只是准备了要从键盘中读取数据
		buf = new BufferedReader(new InputStreamReader(System.in)) ;
		String str = null ;
		for(int i=0;i<2;i++){
			try{
				System.out.print("请输入内容:") ;
				str = buf.readLine() ;
			}
			catch (Exception e){
			}
			System.out.println("输入的内容为:"+str) ;
			System.out.println("--------------------------------") ;
		}
	}
}
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值