Java IO流->處理流->標準輸入輸出流:System.in&System.out

圖一:

示例代碼:

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.junit.Test;

public class TestOtherStream {
	/**
	 * 標準輸入流:System.in	返回InputStream類型
	 */
	//與test3()相比,更值得推薦
	@Test
	public void test2() {
		BufferedReader br = null;
		try {
			InputStream is = System.in;//標準輸入流
			InputStreamReader isr = new InputStreamReader(is);//將字節流轉化爲字符流
			br = new BufferedReader(isr);
			BufferedInputStream bis = new BufferedInputStream(is);
			
			String str;
			while(!(str = br.readLine()).equalsIgnoreCase("e") && !str.equalsIgnoreCase("exit")) {
				System.out.println(str.toUpperCase());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	//直接用字節流進行處理,相比之下,test2()將字節流轉換成字符流再進行處理更直觀
	@Test
	public void test3() {
		BufferedInputStream bis = null;
		try {
			InputStream is = System.in;
			bis = new BufferedInputStream(is);
			byte[] b = new byte[1024];
			int len;
			while(true) {
				len = bis.read(b);
				if(len == 1 && (char)b[0] == 'e') break;
				System.out.print(new String(b , 0 ,len).toUpperCase());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}


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