示意图:
代码示例:
public class TestOtherStream { /** * 如何实现字节流与字符流之间的转换: * 转换流:InputStreamReader OutputStreamWriter * 编码:字符串 ----> 字节数组 * 解码:字节数组 ----> 字符串 */ @Test public void test1() { BufferedReader br = null; BufferedWriter bw = null; try { //解码 File file = new File("hello.txt"); FileInputStream fis = new FileInputStream(file); //字节输入流 InputStreamReader isr = new InputStreamReader(fis, "GBK"); //把字节输入流存到输入流读取器 br = new BufferedReader(isr); //缓冲字符输入流 读取 输入流读取器 //编码 File file1 = new File("hello2.txt"); FileOutputStream fos = new FileOutputStream(file1); //字节输出流 OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK"); //字节输出流存到输出流编写器 bw = new BufferedWriter(osw); //缓冲字符输出流 读取 输出流编写器 String str; while ((str = br.readLine()) != null) { bw.write(str); bw.newLine(); bw.flush(); } } catch (IOException e) { e.printStackTrace(); } finally { if (bw != null){ try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } if (br != null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } }