java txt文件utf-8转GBK的问题

今天在通信的时候遇到一个问题。我需要将本地的一个TXT文件(utf-8)发送到以BASE64编码post到一个接口,但接口中却使用的是gbk,导致了TXT中的汉字乱码!有什么办法可以解决?可以转文件,实在不行转文件中的内容(字符串)也可以。回答new String(xxx.getBytes, "gbk")的就别费劲了。根本不能用!找真心能解决的大神!只有10点,全给了!

步骤一:直接把文件备份。

步骤二:打开文件,选择“另存为”。

步骤三:编码格式从“UTF-8"切换到“GBK”(默认)。保存即可。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-19
package com.mkyong;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class UTF8ToGBK {
public static void main(String[] args) throws Exception {

File fileDir = new File("/home/user/Desktop/Unsaved Document 1");

BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(fileDir), "UTF-8"));

String str;

while ((str = in.readLine()) != null) {
System.out.println(str);// java内部只有unicode编码 所以str是unicode编码
String str2 = new String(str.getBytes("GBK"), "GBK");// str.getBytes("GBK")是gbk编码,但是str2是unicode编码
System.out.println(str2);
}

in.close();
}
}

 问题的关键是new String(xxx.getBytes("gbk"), "gbk")这句话是什么意思,xxx.getBytes("gbk")是GBK编码,所以java是不能够正确输出的,因此必须通过new String(xxx.getBytes("gbk"), "gbk")把xxx.getBytes("gbk")的GBK编码变成unicode编码,因此你要的GBK就是str.getBytes("GBK")这就是GBK编码,不过你是不能够输出的,因此java不支持输出GBK

String fullStr = new String(str.getBytes("UTF-8"), "UTF-8");//正常
String fullStr2 = new String(str.getBytes("UTF-8"), "GBK");//不正常,编码不一致UTF-8的编码怎么能够解读为 GBK

看一下jdk文档是怎么说的

public String(byte[] bytes,
      Charset charset)

Constructs a new String by decoding the specified array of bytes using the specified charset.

str.getBytes("GBK")

应该就是你要传递给接口的

那现在的问题就是,我怎么在String中持有GBK编码的东西呢?

String str3 = new String(str.getBytes("GBK"),"ISO-8859-1");
System.out.println(new String(str3.getBytes("ISO-8859-1"),"GBK"));

str3就是可以传递给后台的的字符串

本回答被提问者采纳
第2个回答  2018-12-05

网页链接这个链接可以解决,本人博客!!!

第3个回答  2013-12-19
转换ISO-8859-1然后再转GBK
第4个回答  2013-12-18
最简单的办法,就是把你的文件另存为UTF-8呗~~
相似回答