Java 转换流:InputStreamReader & OutputStreamWriter

package com.io.review;

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

import org.junit.Test;

/**
 * 转换流:InputStreamReader & OutputStreamWriter
 */
public class BufferedStreamCopy {

	/*
	 * 编码 1 【编码:字符串 -> 字节数组】
	 */
	@Test
	public void coding() {
		String str = "自定义编码 嘿 Siri !";
		BufferedWriter bw = null;
		try {
			// 将str 写入当前项目下./hello.txt 文件中
			FileOutputStream fos = new FileOutputStream("./hello.txt");
			OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");// 此处也可指定编码格式
			bw = new BufferedWriter(osw);

			bw.write(str);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bw != null) {
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	/*
	 * 解码 1 【解码:字节数组 -> 字符串】
	 */
	@Test
	public void decode() {
		BufferedReader br = null;
		try {
			InputStream in = System.in;
			InputStreamReader isr = new InputStreamReader(in);
			br = new BufferedReader(isr);

			String str = null;
			while ((str = br.readLine()) != null) {
				System.out.println("---" + str);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/*
	 * 解码 2
	 * 
	 * 从键盘输入字符串,要求将读取到的整行字符串转成大写输出。当输入“e”或者“exit”时,退出程序。
	 */
	@Test
	public void decode2() {
		BufferedReader br = null;
		try {
			InputStream in = System.in;
			InputStreamReader sir = new InputStreamReader(in);
			br = new BufferedReader(sir);

			String str = null;
			while ((str = br.readLine()) != null) {
				// 忽略大小写判断是否 e或 exit
				if (str.equalsIgnoreCase("e") || str.equalsIgnoreCase("exit")) {
					System.out.println("程序结束!!");
					break;
				} else {
					// 输入的字符转换成大写
					String upperCase = str.toUpperCase();
					System.out.println(upperCase);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	/*
	 * 解码 3
	 */
	@Test
	public void decode3() {
		BufferedReader br = null;
		try {
			FileInputStream fis = new FileInputStream("./hello.txt");
			InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
			br = new BufferedReader(isr);

			String str = null;
			while ((str = br.readLine()) != null) {
				System.out.println(str);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}