如何使用java扫描仪读取非英语字符?
那里 我正在制作此应用程序以更改字幕文件。 当我测试它时,我遇到了一个奇怪的问题,例如,当我在非英语波斯语上测试它时,程序无法读取文件。 以下是我在节目中阅读字幕的方式:如何使用java扫描仪读取非英语字符?,java,java.util.scanner,subtitle,Java,Java.util.scanner,Subtitle,那里 我正在制作此应用程序以更改字幕文件。 当我测试它时,我遇到了一个奇怪的问题,例如,当我在非英语波斯语上测试它时,程序无法读取文件。 以下是我在节目中阅读字幕的方式: Scanner sub = null; try { sub = new Scanner(new File(address)); } catch (FileNotFoundException ex) { ex.printStackTrace(); } while(sub.h
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文件位置的字符串
我应该怎么做才能让程序读取文件?在创建扫描仪时选择不同的编码 类似于这一点的东西可能会起作用:
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);
}
找到写入文件的编码,并将其提供给Scanner构造函数。