javaIO流及鍵盤輸入保存到文件中

流是一組有序的數據序列java

源。。。。流:都有多是文件,網絡,壓縮包,網絡

流按操做數據分爲字節流和字符流   app

字節流按照一個字節8位來讀(8位都是01010101類型的)ui

字符流按照一個字符來讀編碼

流按流向分爲輸入流和輸出流.net

例子:鍵盤輸入而後存到硬盤的文件裏面(多行輸入)code

package suibian;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Test {

	public static void main(String[] args) {
		String targetPath = "d:/keyBoard/input.txt";
		File targetFile = new File(targetPath);//準備文件接收他
		
		String msg = null;
		InputStream is = null;
		InputStreamReader  isr = null;
		BufferedReader br = null;
		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;
		
		
		try {//控制檯獲得GBK字符,他會自動幫你轉字節
			is = System.in; //流引用盡可能在代碼塊中執行
			isr = new InputStreamReader(is,"UTF-8");////而後你讀字符按照GBK的格式把本身讀入的字節轉成GBK編碼的字符
			br = new BufferedReader(isr);
			/*FileOutputStream(File file, boolean append) 
			Creates a file output stream to write to the file represented by the specified File object*/
			fos = new FileOutputStream(targetFile, true);
			//輸出的時候把字節按照utf-8的格式輸出來,由於utf-8的格式包含GBk,utf-8更加靈活
			osw = new OutputStreamWriter(fos, "UTF-8");
			bw = new BufferedWriter(osw);
			
			while (true) {
				msg = br.readLine();
				System.out.println(msg);
				if ("over".equals(msg)) {
					break;
				}
				bw.write(msg, 0, msg.length());
				bw.newLine();
				bw.flush();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != is) {
					is.close();
				}
				
				if (null != isr) {
					isr.close();
				}
				
				if (null != br) {
					br.close();
				}
				
				if (null != fos) {
					fos.close();
				}
				
				if (null != osw) {
					osw.close();
				}
				
				if (null != bw) {
					bw.close();
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
		
		
		
		
	}

}

優秀博客:http://blog.csdn.net/jierong01/article/details/53394161?locationNum=1&fps=1blog

http://blog.csdn.net/zhangliangzi/article/details/51226652utf-8

相關文章
相關標籤/搜索