进阶day10-转换流_指定编码读取(InputStreamReader)
This commit is contained in:
50
javaSE-day10/src/com/inmind/transfer_stream02/Demo09.java
Normal file
50
javaSE-day10/src/com/inmind/transfer_stream02/Demo09.java
Normal file
@@ -0,0 +1,50 @@
|
||||
package com.inmind.transfer_stream02;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
/*
|
||||
转换流_指定编码读取(InputStreamReader)
|
||||
InputStreamReader是从字节流到字符流的桥梁:解码
|
||||
|
||||
构造方法:
|
||||
InputStreamReader(InputStream in) 创建一个使用默认字符集的InputStreamReader。
|
||||
InputStreamReader(InputStream in, String charsetName) 创建一个使用命名字符集的InputStreamReader。
|
||||
常用方法:
|
||||
close()
|
||||
int read(); 读取一个字符
|
||||
int read(char[] chars) 读取一个字符数组
|
||||
|
||||
注意:转换流的作用是指定编码方式去读写文件
|
||||
*/
|
||||
public class Demo09 {
|
||||
//指定gbk编码方式去读取指定gbk文件
|
||||
public static void main(String[] args) throws IOException {
|
||||
//InputStreamReader(InputStream in, String charsetName) 创建一个使用命名字符集的InputStreamReader。
|
||||
InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\io_test\\file_gbk.txt"),"gbk");
|
||||
char[] chars = new char[1024];
|
||||
int len = -1;
|
||||
while ((len = isr.read(chars)) != -1) {
|
||||
System.out.println(new String(chars,0,len));
|
||||
}
|
||||
|
||||
isr.close();
|
||||
}
|
||||
|
||||
//指定utf-8编码方式去读取指定文件
|
||||
public static void readUtf8(String[] args) throws IOException {
|
||||
//InputStreamReader(InputStream in) 创建一个使用默认字符集的InputStreamReader。
|
||||
// InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\io_test\\file_utf8.txt"));
|
||||
//InputStreamReader(InputStream in, String charsetName) 创建一个使用命名字符集的InputStreamReader。
|
||||
InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\io_test\\file_utf8.txt"),"utf-8");
|
||||
char[] chars = new char[1024];
|
||||
int len = -1;
|
||||
while ((len = isr.read(chars)) != -1) {
|
||||
System.out.println(new String(chars,0,len));
|
||||
}
|
||||
|
||||
isr.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user