23种设计模式---适配器模式

package com.bjpowernode.demo03;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

/**

  • 转换流
  • InputStreamReader/OutputStreamWriter
  • 当读写的文本文件编码格式与当前环境的编码格式不一样时, 就使用转换流
  • 这两个类采用了 适配器设计模式
  • @author Administrator

*/
public class Test03 {

public static void main(String[] args) throws IOException {

// readFile();
writeFile();
}

//把文本写到d:/hehe.txt文件中, 要求文件使用GBK编码, 当前环境使用UTF-8
private static void writeFile() throws IOException {
	OutputStream out = new FileOutputStream("d:/hehe.txt");
	//以GBK编码把字符转换为字节流,输出到out中
	OutputStreamWriter osw = new OutputStreamWriter(out, "GBK");
	
	osw.write("hello");
	osw.write("\r\n");
	osw.write("也可以写中文的字符串, 文件的编码是GBK格式");
	osw.close();
}

// 读取d:/out.txt文件, 该文件使用GBK编码, 当前环境使用UTF-8编码
private static void readFile() throws IOException {
	InputStream in = new FileInputStream("d:/out.txt"); 
	//以GBK编码把 字节流in中的字节转换为字符
	InputStreamReader isr = new InputStreamReader(in, "GBK");
	
	int cc = isr.read();
	while( cc != -1){
		System.out.print((char)cc);
		cc = isr.read();
	}
	
	isr.close();
}

}

猜你喜欢

转载自blog.csdn.net/qq_30347133/article/details/83513276