Convert known encoding file to UTF-8

I need to convert a text file to String, which finally I have to put as input parameter (type InputStream) in IFile.create (Eclipse) file. Look for an example or how to do it, but you still cannot understand ... your help is needed!

just for testing, I tried to convert the original text file to UTF-8 encoded with this code

FileInputStream fis = new FileInputStream(FilePath); InputStreamReader isr = new InputStreamReader(fis); Reader in = new BufferedReader(isr); StringBuffer buffer = new StringBuffer(); int ch; while ((ch = in.read()) > -1) { buffer.append((char)ch); } in.close(); FileOutputStream fos = new FileOutputStream(FilePath+".test.txt"); Writer out = new OutputStreamWriter(fos, "UTF8"); out.write(buffer.toString()); out.close(); 

but I even thought that the final * .test.txt file is UTF-8 encoded, the characters inside are corrupted.

+4
java eclipse encoding unicode utf-8
source share
1 answer

You need to specify the encoding of InputStreamReader using the Charset parameter.

  // ↓ whatever the input encoding is Charset inputCharset = Charset.forName("ISO-8859-1"); InputStreamReader isr = new InputStreamReader(fis, inputCharset)); 

This also works:

 InputStreamReader isr = new InputStreamReader(fis, "ISO-8859-1")); 

See also:

SO search where I found all these links: https://stackoverflow.com/search?q=java+detect+encoding


You can get the default encoding that comes from the system the JVM is working with at run time through Charset.defaultCharset() .

+9
source share

All Articles