查看API文档,发现是字节流通向字符流的桥梁。查看构造,可以传递字节流,可以指定编
工作。该流是一个Reader的子类,是字符流的体系。所以将转换流称之为字节流和字符流
之间的桥梁。
InputStreamReader 是字节流通向字符流的桥梁
测试InputStreamReader:
第一步: 需要专门新建以GBK编码的文本文件。为了便于标识,我们命名为gbk.txt
和以UFT-8编码的文本文件,命名为utf.txt
第二步: 分别写入汉字”中国”
第三步:编写测试方法,用InputStreamReader 分别使用系统默认编码,GBK,
UTF-8编码读取文件.
public class Demo1 {
public static void main(String[] args) throws Exception {
File file = new File("./src/a.txt");
File gbkFile = new File("./src/gbk.txt");
File utfFile = new File("./src/utf.txt");
testReadFile(gbkFile);
System.out.println("====================");
testReadFile(utfFile, "gbk");
System.out.println("====================");
testReadFile(file, "utf-8");
}
private static void testReadFile(File file, String string) throws Exception {
FileInputStream fis = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fis,string);
int content = 0;
while((content = reader.read())!=-1){
System.out.print((char)content);
}
reader.close();
System.out.println("");
}
private static void testReadFile(File file) throws Exception {
FileInputStream fis = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fis);
int content = 0;
while((content = reader.read())!= -1){
System.out.print((char)content);
}
reader.close();
System.out.println("");
}
}
OutputStreamWriter
有了InputStreamReader 可以转换InputStream
那么其实还有OutputStreamWriter 可以转换OutputStream
OutputStreamWriter 是字符流通向字节流的桥梁
测试OutputStreamWriter
一: 分别使用OutputStreamWriter使用系统默认编码,GBK,UTF-8相对应的默认
编码文件,GBK编码文件,UTF-8编码文件中写出汉字”中国”.
二: 在使用上述案例中的readFile方法传入相对应码表读取.
public class TestIo {
public class Demo4 {
public static void main(String[] args) throws IOException {
File file = new File("c:\\a.txt");
File fileGBK = new File("c:\\gbk.txt");
File fileUTF = new File("c:\\utf.txt");
testWriteFile(file);
testWriteFile(fileGBK, "gbk");
testWriteFile(fileUTF, "utf-8");
testReadFile(file);
testReadFile(fileGBK, "gbk");
testReadFile(fileUTF, "utf-8");
}
private static void testWriteFile(File file) throws IOException {
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter ops = new OutputStreamWriter(fos);
ops.write("中国");
ops.close();
}
private static void testWriteFile(File file, String encod)
throws IOException {
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter ops = new OutputStreamWriter(fos, encod);
ops.write("中国");
ops.close();
}
private static void testReadFile(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
InputStreamReader ins = new InputStreamReader(fis);
int len = 0;
while ((len = ins.read()) != -1) {
System.out.print((char) len);
}
ins.close();
}
private static void testReadFile(File file, String encod)
throws IOException {
FileInputStream fis = new FileInputStream(file);
InputStreamReader ins = new InputStreamReader(fis, encod);
int len = 0;
while ((len = ins.read()) != -1) {
System.out.print((char) len);
}
ins.close();
}
}