java文件字符读取,如何读取具有特定字符编码的Java文件?

I am trying to read a file in as either UTF-8 or Windows-1252 depending on the output of this method:

public Charset getCorrectCharsetToApply() {

// Returns a Charset for either UTF-8 or Windows-1252.

}

So far, I have:

String fileName = getFileNameToReadFromUserInput();

InputStream is = new ByteArrayInputStream(fileName.getBytes());

InputStreamReader isr = new InputStreamReader(is, getCorrectCharsetToApply());

BufferedReader buffReader = new BufferedReader(isr);

The problem I'm having is converting the BufferedReader instance to a FileReader.

Furthermore:

The name of the file itself (fileName) cannot be trusted to be a particular Charset; sometime the file name will contain UTF-8 characters, and sometimes Windows-1252. Same goes for the file's content (however if file name and file content will always have matching charsets).

Only the logic inside getCorrectCharsetToApply() can select the charset to apply, so attempting to read a file by its name prior to calling this method could very well result with, Java trying to read the file name with the wrong encoding...which causes it to die!

Thanks in advance!

解决方案

So, first, as a heads up, do realize that fileName.getBytes() as you have there gets the bytes of the filename, not the file itself.

Second, reading inside the docs of FileReader:

The constructors of this class assume that the default character

encoding and the default byte-buffer size are appropriate. To specify

these values yourself, construct an InputStreamReader on a

FileInputStream.

So, sounds like FileReader actually isn't the way to go. If we take the advice in the docs, then you should just change your code to have:

String fileName = getFileNameToReadFromUserInput();

FileInputStream is = new FileInputStream(fileName);

InputStreamReader isr = new InputStreamReader(is, getCorrectCharsetToApply());

BufferedReader buffReader = new BufferedReader(isr);

and not try to make a FileReader at all.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值