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("--------------------------------") ;
		}
	}
}
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章