I am trying read UTF-16 encoded file in JDK 7, can anyone help me out. I can able to read in Python by:

fread = open(r'sample.dat', 'rb').read()
mytext = fread.decode('utf-16')
print mytext

I tried so many ways in java 7 but not succeeded. Thanks in advance.

Re: Can anyone tell me how to read UTF-16 encoded file in java 7 ?? 80 80

You need an InputStreamReader to read and decode text using UTF-16 encoding. You specify the charset when creating the InputStreamReader, eg
InputStreamReader in = new InputStreamReader(myInputStream, StandardCharsets.UTF_16);
Anything you read from that stream will now be interpreted as UTF-16. Depending on your file's byte ordering you may need to use UTF_16BE or UTF_16LE instead.

So: create an FileInputStream for your file, create an InputStreamReader from the FileInputStream, and optionally, wrap that in a BufferedReader for efficiency, then simply read the lines from the file.

ps: I tagged this 'java' so the right people will see it.

Re: Can anyone tell me how to read UTF-16 encoded file in java 7 ?? 80 80

Thank you very much i got the solution by using UTF_16LE.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.