How to read non-english characters with Scanner ja

2020-03-08 06:24发布

问题:

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