Frage

If I pass in a UTF-16 encoded file to the following code then will I get an UnsupportedEncodingException?

    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
        String ip;
        while ((ip = br.readLine()) != null){
            //do something
        }
    } catch (UnsupportedEncodingException use) { 
        //when can I expect an exception?
    }

I have tried this with a UTF-16 file but I am not getting any exception. The reader somehow tries to read all the characters which causes it to read more line than expected. For example in a sample file with 3 lines the reader reads 5 lines, 2 of which are empty lines.

War es hilfreich?

Lösung

UnsupportedEncodingException is only thrown if the name of the charset you pass to the Charset.forName() is not supported. It does not relate to the content of the stream (the Exception is declared to be thrown by the Charset.forName() not by BufferedReader or InputStreamReader classes).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top