Java字符转换为UTF-8

Raf*_*ael 2 java

我在用:

InputStreamReader isr = new InputStreamReader(fis, "UTF8");
Run Code Online (Sandbox Code Playgroud)

从文本文件中读取字符并将其转换为UTF8字符.

我的问题是,如果被读取的一个字符无法转换为utf8,会发生什么?会有例外吗?或者会让角色掉线?

Ara*_*ram 7

你没有从一个charset转换到另一个charset.您只是指示该文件是UTF 8编码,以便您可以正确读取它.

如果您想从1编码转换为另一种编码,那么您应该执行以下操作

File infile = new File("x-utf8.txt");
File outfile = new File("x-utf16.txt");

String fromEncoding="UTF-8";
String toEncoding="UTF-16";

Reader in = new InputStreamReader(new FileInputStream(infile), fromEncoding);
Writer out = new OutputStreamWriter(new FileOutputStream(outfile), toEncoding);
Run Code Online (Sandbox Code Playgroud)

在完成David Gelhar的回复后,我觉得这段代码可以改进一下.如果您不知道"inFile"的编码,则使用GuessEncoding库检测编码,然后使用检测到的编码构建阅读器.