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.

Recommended Answers

All 2 Replies

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.

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 developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.