gpt4 book ai didi

java - 如何在Java中设置文件的下一个编码

转载 作者:行者123 更新时间:2023-11-30 06:06:14 24 4
gpt4 key购买 nike

这是我的代码,它正在读取文件并在特定行上替换文本,但是当读取(readAllLines方法)行时,它在文件中有一个与指定的字符集不匹配的符号,它会抛出 MalformedInputException。例如:我正在阅读带有 UTF_8 字符集的文本,但在文件中它有符号“†”,它会抛出 MIE。

我想问您如何在下面的代码中检查何时发现 MalformedInputException 并尝试下一个编码。例如,当编码为 UTF_8 时,尝试下一个 UTF_16 等,当它匹配时才能正确读取文件。

public boolean replaceTextInSpecificLine(String fileName, int lineNumber, String content, Charset cs)
{
try
{

scan = new Scanner(System.in);
File filePath = readFile(fileName, true);
List<String> lines = null;
if(filePath !=null)
{
lines = Files.readAllLines(filePath.toPath(), cs);


while (lineNumber < 0 || lineNumber > lines.size() - 1)
{
System.out.print("Wrong line number or the file is empty! Enter another line: ");
lineNumber = scan.nextInt();
scan.nextLine();
}
lines.set(lineNumber - 1, content);
Files.write(filePath.toPath(), lines, cs);
System.out.println("Successfully saved!");

return true;
}

}

catch(IOException e)
{

e.printStackTrace();

}
finally
{
close(scan);
}
return false;
}

最佳答案

我会避免在读取文件时切换编码,而只需使用下一个编码重新读取文件。像这样的东西就足够了:

List<String> getAllLines(File file, Charset... charsets) {
for (Charset cs: charsets) {
try {
return Files.readAllLines(file.toPath(), cs);
} catch (MalformedInputException e) {
...
} catch (IOException e) {
...
}
}
// error
}

(这只是一个例子,您的论点可能会根据需要而有所不同)如果您在阅读文档时切换编码,则可能会将某些字符解释为有效的 UTF-8 字符,而实际上它们是 ISO-8859-1 字符。

关于java - 如何在Java中设置文件的下一个编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51265204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com