繁体   English   中英

如何使用Scanner Java读取非英语字符?

[英]How to read non-english characters with 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文件的字符串保留位置。

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

创建Scanner时,请选择其他编码。

遵循此思路的某些方法可能会起作用:

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

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

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

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

 /**
 * 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM