java - 如何在Java中为文件设置下一个编码
问题描述
这是我的代码,它正在读取文件并在特定行上替换文本,但是当读取(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 字符。
推荐阅读
- angular - Nodejs Httpclient JSONP:未定义jsonCallback
- c++ - 什么是相对顺序,stable_partition 有什么作用?
- reactjs - 我可以在蚂蚁设计的速率组件中添加边框吗?
- reactjs - 从预先存在的模板在 React 中创建计算器
- android - xamarin 条码扫描与手电筒
- wix - SourceProperty as Nested Directory in CopyFile
- terraform - 阿里云CMS报警不显示数据
- php - createView 上的会话错误 - Symfony 5.0
- javascript - Chartjs 计算图表中的元素
- python - 在pyomo python中定义因变量