software-mariodiana
7/20/2015 - 8:34 PM

Reading in a file that must be decoded using a particular character set (in this case UTF-16 LE).

Reading in a file that must be decoded using a particular character set (in this case UTF-16 LE).

import java.io.*;
import java.nio.*;

public class UtfDemo {
    public static void main(String[] args) throws IOException {
        
        String filename = "C:\\Users\\mario\\Desktop\\SampleFile.xml";
        
        Charset utf = StandardCharsets.UTF_16LE;
        byte[] buffer = new byte[8192];
        int length;
        
        try (InputStream input = 
                new DataInputStream(new FileInputStream(new File(filename)))) {
            
            while ((length = input.read(buffer)) > -1) {
                // Specify length, or the final iteration will have crud left 
                // over from the previous read, if the current read doesn't 
                // manage to (coincidently) overwrite the entire buffer.
                System.out.print(utf.decode(ByteBuffer.wrap(buffer, 0, length)).toString());
            }
        }
        
        System.out.println();
    }
}