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.

Dani AI

Generated

Brief expert note: was correct that the JVM needs a Reader set to the right UTF-16 variant, and ’s follow-up shows the file was little‑endian (UTF‑16LE). The common gap people hit after that is byte‑order handling and the BOM — here are concise, practical points to avoid surprises.

UTF‑16 files often start with a BOM: 0xFF 0xFE means UTF‑16LE, 0xFE 0xFF means UTF‑16BE. If a BOM is present, a charset that understands it will pick the right endianness; if you force UTF‑16LE/BE explicitly, you may need to skip the BOM yourself. If there is no BOM, you must know the producer’s convention or agree on one.

If you prefer a simple file‑based approach (works in Java 7), read the bytes, detect the first two bytes, then decode while skipping the BOM when necessary:

byte[] b = java.nio.file.Files.readAllBytes(java.nio.file.Paths.get("sample.dat"));
String text;
if (b.length >= 2 && (b[0] == (byte)0xFF && b[1] == (byte)0xFE)) {
  text = new String(b, 2, b.length - 2, "UTF-16LE"); // skip LE BOM
} else if (b.length >= 2 && (b[0] == (byte)0xFE && b[1] == (byte)0xFF)) {
  text = new String(b, 2, b.length - 2, "UTF-16BE"); // skip BE BOM
} else {
  text = new String(b, "UTF-16"); // fallback (may rely on BOM)
}

Tips: for very large files stream and detect BOM with a BufferedInputStream (mark/reset) or use a library BOMInputStream; after decoding, trim a leading U+FEFF if it appears (check text.charAt(0) == '\uFEFF'). If the file came from Windows Notepad/PowerShell it is commonly UTF‑16LE with a BOM — that explains why UTF_16LE fixed the OP’s issue.

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, networking, learning, and sharing knowledge.