Java IO流读取中文

一、使用FileInputStream 字节流正确读取中文
1. 必须了解文本是以哪种编码方式保存字符的
2. 使用字节流读取了文本后,再使用对应的编码方式去识别这些数字,得到正确的字符

  private static void inputStreamChina() {
		// TODO Auto-generated method stub
		File f=new File("D:/BugReport.txt");
		try (FileInputStream fis=new FileInputStream(f)){
			byte[] bytes=new byte[(int) f.length()];
			fis.read(bytes);
//			window记事本默认编码方式是gbk,如果保存文件以UTF-8保存,便以UTF-8读出
//			String str = new String(bytes,"GBK");
            String str = new String(bytes,"UTF-8");
            System.out.println(str);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

二、用FileReader 字符流正确读取中文
FileReader得到的是字符,所以一定是已经把字节根据某种编码识别成了字符了,
而FileReader使用的编码方式是Charset.defaultCharset()的返回值,如果是中文的操作系统,就是GBK
FileReader是不能手动设置编码方式的,为了使用其他的编码方式,只能使用InputStreamReader来代替

private static void FileReaderChina() {
//		使用默认编码方式读取
		File f=new File("D:/BugReport.txt");
		System.out.println("默认编码方式:"+Charset.defaultCharset());
		//FileReader得到的是字符,所以一定是已经把字节根据某种编码识别成了字符了
        //而FileReader使用的编码方式是Charset.defaultCharset()的返回值,如果是中文的操作系统,就是GBK
		try(FileReader fr=new FileReader(f)) {
			char[] chars=new char[(int) f.length()];
			fr.read(chars);
			System.out.printf("FileReader会使用默认的编码方式%s,识别出来的字符是:%n",Charset.defaultCharset());
			System.out.println(new String(chars));
		} catch (Exception e) {
			// TODO: handle exception
		}
//		使用指定编码方式读取
		//FileReader是不能手动设置编码方式的,为了使用其他的编码方式,只能使用InputStreamReader来代替
        //并且使用new InputStreamReader(new FileInputStream(f),Charset.forName("UTF-8")); 这样的形式
		try (InputStreamReader isr=new InputStreamReader(new FileInputStream(f)
				,Charset.forName("UTF-8"))){
			char[] chars=new char[(int) f.length()];
			isr.read(chars);
			System.out.println(new String(chars));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值