如何用Scanner java读取非英文字符?

时间:2013-08-08 21:02:29

标签: java java.util.scanner subtitle

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

    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文件的字符串保存位置。

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

2 个答案:

答案 0 :(得分:7)

创建Scanner时选择其他编码。

这可能有用:

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

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

您可以阅读有关编码here的更多信息。

答案 1 :(得分:1)

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

 /**
 * Constructs a new <code>Scanner</code> 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);
}