无法将字符串转换为正确的编码格式
问题描述:
简而言之,我必须创建一个Java程序,该程序从输入文件中读取行并显示在System.out语句中读取的文本。文件中的其中一行是“是不是有点”。 Java然后读取这条线作为“这不是有点”。问题是撇号正在被读作“”“。我一直在寻找许多论坛帖子,并且找不到能将“转换”回撇号的解决方案。我搜索了什么““甚至是什么,它说这意味着输入是UTF-8格式?我如何将它转换为在System.out语句中正确读取的格式。 另外,我不能蛮力强制将所有出现的'转换成撇号的语句,因为可能有其他UTF-8编码文本会导致问题,所以我不能只是蛮横地强制每一种可能性。无法将字符串转换为正确的编码格式
答
看起来您正在使用Windows-1252编码来读取文件。这里有很好的表格显示了两种编码标准之间的转换。 http://www.i18nqa.com/debug/utf8-debug.html
该字符实际上并不是'
,而是实际上是’
。您可以指定在读取文件时使用的编码。看下面的例子。
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ReadFile {
public static void main(String[] args) throws IOException {
final ReadFile readFile = new ReadFile();
readFile.read("Windows-1252");
readFile.read("UTF-8");
}
private void read(final String charsetName) throws IOException {
//Java 8 version
Files.lines(Paths.get("myFile.txt"), Charset.forName(charsetName)).forEach(System.out::println);
//Older Java version
final BufferedReader bufferedReader2 = new BufferedReader(
new InputStreamReader(new FileInputStream("myFile.txt"), charsetName));
String currentLine;
while ((currentLine = bufferedReader2.readLine()) != null) {
System.out.println(currentLine);
}
}
}
+0
这对我有用。谢谢! – user3858843
答
如果您想在文件读取时指定编码,可以试试这个。
Reader reader = new InputStreamReader(new FileInputStream("path"), "UTF-8"));
什么是用于创建文件的编码? – MordechayS