如何用Scanner java阅读非英语字符?

在那里我正在制作这个应用程序来改变字幕文件。 当我测试它时,我遇到了一个奇怪的问题,当我在非英语(例如波斯语)上测试它时,程序将无法读取该文件。 这就是我在程序中阅读字幕的方式:

Scanner sub = null; try { sub = new Scanner(new File(address)); } catch (FileNotFoundException ex) { ex.printStackTrace(); } while(sub.hasNext()){ String sentence = sub.nextLine(); //some magical stuff here :) } 

其中address是.srt文件的String保存位置。

我应该怎么做才能让程序读取文件?

创建Scanner时选择不同的编码。

这可能有用:

 new Scanner(new File(address), "UTF-16"); 

这将更改扫描程序以使用UTF-16编码读取文件。

您可以在此处阅读有关编码的更多信息 。

这是我可以从java doc中找到的构造函数。 尝试找到输入文件的编码并使用此构造函数。 我认为这应该有效。

  /** * Constructs a new Scanner that produces values scanned * from the specified input stream. Bytes from the stream are converted * into characters using the specified charset. * * @param source An input stream to be scanned * @param charsetName The encoding type used to convert bytes from the * stream into characters to be scanned * @throws IllegalArgumentException if the specified character set * does not exist */ public Scanner(InputStream source, String charsetName) { this(makeReadable(source, charsetName), WHITESPACE_PATTERN); }