Convert Shift_JIS format to UTF-8 format

一世执手 提交于 2019-12-01 01:45:41

The answer @VicJordan posted is not correct. When you call getBytes(), you are getting the raw bytes of the string encoded under your system's native character encoding (which may or may not be UTF-8). Then, you are treating those bytes as if they were encoded in UTF-8, which they might not be.

A more reliable approach would be to read the Shift_JIS file into a Java String. Then, write out the Java String using UTF-8 encoding.

InputStream in = ...
Reader reader = new InputStreamReader(in, "Shift_JIS");
StringBuilder sb = new StringBuilder();
int read;
while ((read = reader.read()) != -1){
  sb.append((char)read);
}
reader.close();

String string = sb.toString();

OutputStream out = ...
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write(string);
writer.close();

Finally i found the solution. Was doing some very basic mistake. Below code is working perfectly fine:

InputStream inputStream = getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "Shift_JIS"));
byte[] b = line.getBytes();
String value = new String(b, "UTF-8");

If you want to copy inFile (SHift_JIS) to outFile (UTF-8).

try (Reader reader = new InputStreamReader(new FileInputStream(inFile), "Shift_JIS");
    Writer writer = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8")) {
    char[] buffer = new char[4096];
    int size;
    while ((size = reader.read(buffer)) >= 0)
        writer.write(buffer, 0, size);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!