查看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();
}
}