How to read non-english characters with Scanner java?

笑着哭i 提交于 2019-12-19 04:55:16

问题


there I'm making this app to change subtitle files. when I was testing it I faced a strange problem, when I was testing it on non-english (persian for instance) the program wouldn't read the file. this is how I read subtitles in my program:

    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 :)
}

where address is a String keeping place of .srt file.

what should I do so the program reads the file?


回答1:


Select a different encoding when creating the Scanner.

Something along the lines of this might work:

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

This will change the scanner to read the file using a UTF-16 encoding.

You can read up more on encodings here.




回答2:


This is the constructor I could find from the java doc. Try to find the encoding for your input file and use this constructor. I think this should work.

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


来源:https://stackoverflow.com/questions/18136045/how-to-read-non-english-characters-with-scanner-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!