Reading a UTF-16 encoded file in java and writing back into it.

I have had recent troubles in reading from file which i didnt know was UTF-16 encoded. So i was getting some weird kind of output when i tried printing it. So on googling and with someone’s help, i was able to resolve the problem and want to share this with you guys out there.

First comes reading

Now for reading a file in java as we all know it can be done in a quicker way using the bufferedinputstream.

So what we can do is

File file = new File("File Path");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF16"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
System.out.println(everything);
} finally {
	br.close();
}

Note we used “UTF-16” as a parameter in the FileInputStream to read in that encoding. “UTF-16” is common in log files as well as some files with unknown extension.

A second way to do this is by simply reading the contents of file as you already used to do. And then when you are done after obtaining a string, you can do something like this.

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
try {
        StringBuilder sb = new StringBuilder();
	String line = br.readLine();
	while (line != null) {
		sb.append(line);
		sb.append(System.lineSeparator());
		line = br.readLine();
	}
	String fileContent = sb.toString();
        final String defaultEncoding = Charset.defaultCharset().name();
        final byte[] utfString = fileContent.getBytes(Charset.forName(defaultEncoding));
	fileContent = new String(utfString, Charset.forName("UTF-16"));
} finally {
     br.close();
}

Now you have the content in readable form. You can always try printing if you are not sure.
Now do some appending or modification with the text. and after this you wanna write it back to the file which expects “UTF-16” encoded string. So, we will reconvert the string to be written to “UTF-16” encoding.

Suppose you would be needing to write the string str into file then.

FileOutputStream fs = new FileOutputStream(file);
fs.write(str.toString().getBytes("UTF-16"));
fs.close();

And here we go, you are done.
In case of any queries or suggestions feel free to comment below. I’ll be happy to help you out.
Happy coding guys.