We help IT Professionals succeed at work.
Get Started

Convert files in any unicode encoding type to UTF-8 in Java

ayeen
ayeen asked
on
4,013 Views
Last Modified: 2012-08-13

I have this upload mechanism in our web app and everything is OK if the user just uploads a simple file and this is how part of the code looks:


// raw file
FormFile myFile = myForm.getTheFile();//using struts..so this is defined somewhere in my form bean

// final product should be BufferedReader
BufferedReader read = new BufferedReader(new InputStreamReader(myFile.getInputStream()));


My question is how do you convert files regardless of encoding type to UTF-8? Here are some of the list of extension names that I have to convert (yes i also have to handle big and lil endians):

utxt
utf8
utf-8  
utf16  
utf-16  
utf-16le  
utf-16be  
ucs2 ucs-2
ucs-2le
ucs-2be
cs2le


Now somewhere, I have seen this code (see below) but this just converts a text file to UTF-8:

String asString = new String(contents, "ISO8859_1");//for text file
byte[] newBytes = asString.getBytes("UTF8");


And I have seen this from the java site:

http://java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html


Based on the info in that URL does that mean I just have to change "ISO8859_1" to "UnicodeBig" or "UTF-16" etc depending on what type my raw file is?
Like:

//if Sixteen-bit Unicode Transformation Format, little-endian byte order, with byte-order mark
String asString = new String(contents, "UnicodeLittle");
byte[] newBytes = asString.getBytes("UTF8");


If that is all I have to do how do I cast the byte[] newBytes to BufferedReader? Because BufferedReader should be my final product after converting the files to UTF-8


Thanks in advance!
Comment
Watch Question
Java Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
This problem has been solved!
Unlock 1 Answer and 7 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE