import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
/*
* 转换流 java.io.InputStreamReader 继承Reader
* 字符输入流,读取文本文件
* 字节流向字符的桥梁,将字节流转成字符流
* 读取的方法:
* read():读取1个字符,读取字符数组
* InputStreamReader(InputStream in):接收所有的字节输入流
* InputStreamReader(InputStream in,String charsetName):传递编码表的名字
*/
public class InputStreamReaderDemo {
public static void main(String[] args) throws IOException {
readGBK();
}
/*
* 转化流,InputStreamReader读取文本 采用系统默认编码表,读取GBK文件
*/
public static void readGBK() throws IOException{
//创建字节输入流,传递文本文件
FileInputStream fis=new FileInputStream("d:\\demo\\gbk.txt");
//创建转换流对象,构造方法,包装字节输入流
InputStreamReader isr=new InputStreamReader(fis,"GBK");
char[] ch=new char[2014];
int len=isr.read(ch);
System.out.println(new String(ch,0,len));
isr.close();
}
}
import java.io.IOException;
import java.io.InputStreamReader;
/*
* 转换流 java.io.InputStreamReader 继承Reader
* 字符输入流,读取文本文件
* 字节流向字符的桥梁,将字节流转成字符流
* 读取的方法:
* read():读取1个字符,读取字符数组
* InputStreamReader(InputStream in):接收所有的字节输入流
* InputStreamReader(InputStream in,String charsetName):传递编码表的名字
*/
public class InputStreamReaderDemo {
public static void main(String[] args) throws IOException {
readGBK();
}
/*
* 转化流,InputStreamReader读取文本 采用系统默认编码表,读取GBK文件
*/
public static void readGBK() throws IOException{
//创建字节输入流,传递文本文件
FileInputStream fis=new FileInputStream("d:\\demo\\gbk.txt");
//创建转换流对象,构造方法,包装字节输入流
InputStreamReader isr=new InputStreamReader(fis,"GBK");
char[] ch=new char[2014];
int len=isr.read(ch);
System.out.println(new String(ch,0,len));
isr.close();
}
}
本文通过一个具体的Java InputStreamReader示例,展示了如何使用此类从文件中读取文本数据,并将其从字节流转换为字符流。特别关注了指定编码(如GBK)以确保正确解读文本的重要性。
1631

被折叠的 条评论
为什么被折叠?



