1. 程式人生 > >位元組流和字元流的轉換橋樑

位元組流和字元流的轉換橋樑

1、把從鍵盤輸入的文字寫入到檔案中

package com.rl.tyt.convert;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/**
 * 把從鍵盤輸入的文字寫入到檔案中
 */
public class ScannerDemo {

	public static void main(String[] args) {
		
		//建立Scanner物件
		Scanner sc = new Scanner(System.in);
		BufferedWriter bw = null;		
		try {
			bw = new BufferedWriter(new FileWriter("b.txt"));
			String line = null;
			while((line = sc.nextLine())!=null){
				if("exit".equals(line)){
					break;
				}
				bw.write(line);
				bw.newLine();
				bw.flush();
				
			}
			
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(bw != null){
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}

2、InputStreamReader(把位元組流轉向字元流)

package com.rl.tyt.convert;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
 * InputSteramReader把位元組流轉換為字元流
 * 位元組流轉換為字元流
 */
public class ConvertInDemo {

	public static void main(String[] args) {
		
		InputStream is = System.in;
		//要想使用字元流的高效緩衝區來操作位元組流需要轉換
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		//定義要寫入的檔案流
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter("c.txt"));
			
			
			
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		String line = null;
		try {
			while((line = br.readLine())!=null){
				if("exit".equals(line)){
					break;
				}
				bw.write(line);
				//換行
				bw.newLine();
				bw.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(bw !=null){
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
}

3、OutputStreamWriter(把字元流轉換為位元組流)

package com.rl.tyt.convert;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
/**
 * OutputSteramWriter把字元流轉換為位元組流
 * 字元流轉換為位元組流
 */
public class ConvertOutDemo {

	public static void main(String[] args) throws IOException {
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			br = new BufferedReader(new FileReader("c.txt"));
			//建立字元流向位元組流轉換的物件
			bw = new BufferedWriter(new OutputStreamWriter(System.out));
			String line = null;
			while((line = br.readLine())!=null){
				bw.write(line);
				bw.newLine();
				bw.flush();
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(bw != null){
				bw.close();
			}
			if(br != null){
				br.close();
			}
		}
		
	}
	
}