Syed Ali
Syed Ali

Reputation: 1897

InputStreamReader not throwing UnsupportedEncodingException

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.

Upvotes: 1

Views: 760

Answers (1)

icza
icza

Reputation: 417412

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).

Upvotes: 3

Related Questions