如何解决fileinputstream中文乱码问题?一起了解一下吧!
Java中使用 FileInputStream 读取txt等文档时,中文会产生乱码,这是因为一个中文对应两个字节存储(负数),也就是说,读取对应中文的字节数应该是偶数; 而英文对应一个字节存储。FileInputStream每次读取一个数组长度的字节时,读取的中文字节数可能是奇数,也就是只读到中文的一半字节,出现乱码。
解决方法是:
try {
fis = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fis,"GBK"); //最后的"GBK"根据文件属性而定,如果不行,改成"UTF-8"试试 BufferedReader br = new BufferedReader(reader); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } }
关于解决fileinputstream中文乱码问题,我们就了解到这啦!
FileInputStream流详解
1、FileInputStream概念
FileInputStream流被称为文件字节输入流,意思指对文件数据以字节的形式进行读取操作如读取图片视频等;
2、我们看JDK对FileInputStream描述
3、构造方法摘要
1、FileInputStream(File file):通过打开与实际文件的连接创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。
2、FileInputStream(FileDescriptor fdObj)创建 FileInputStream通过使用文件描述符 fdObj ,其表示在文件系统中的现有连接到一个实际的文件。
3、FileInputStream(String name)通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。
4、通过FileInputStream读取D盘中的 hi.txt 文件
/** 第一种方式:使用 read()方法 1、read()方法每次只读取一个字节 2、read()方法返回值是一个int类型,代码该字符的int值 3、如果返回值为-1,说明读取完毕*/public class $Test03 { public static void main(String[] args) throws Exception { String path = "D:\\hi.txt"; InputStream inputStream = null; try { inputStream = new FileInputStream(path); int resultData; while ((resultData = inputStream.read()) != -1) { System.out.print((char)resultData); } } catch (Exception e) { // TODO: handle exception }finally { inputStream.close(); } }}
/** 使用read(byte[] b)方法读取文件 1、byte[] b = new byte[3];代表一次性去读三个字节方法b数组中 2、read(byte[] b)方法的返回值是读取的字节的长度*/ public static void main(String[] args) throws Exception { String path = "D:\\hi.txt"; InputStream inputStream = null; byte[] b = new byte[3]; try { inputStream = new FileInputStream(path); int resultLength; while ((resultLength = inputStream.read(b)) != -1) { System.out.print(new String(b , 0 , resultLength)); } } catch (Exception e) { // TODO: handle exception }finally { inputStream.close(); } }}