来个简单的问题,UTF-8转GBK

希望对你有帮助 2015-08-12 02:20:09

File file = new File("D:/workspace_a/a/src/a/a.txt");
File fileb = new File("D:/workspace_a/a/src/a/b.txt");
String line= "";
BufferedReader reader =null;
OutputStreamWriter out = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileb)));
out = new OutputStreamWriter(new FileOutputStream(file));
while ((line=reader.readLine())!=null) {
out.write(line);//utf8
String gbkline=utf8ToGbk(line);//这里应该怎么转
out.write("\n");
out.write(gbkline);//gbk
}
} catch (IOException e1) {
e1.printStackTrace();
} finally{
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}


在我本地有两个txt:
a.txt 在eclipse下是GBK编码格式
b.txt 在eclipse下是UTF-8编码格式的
现在我要将b.txt 的中文内容写入到 a.txt 下,现在就涉及到了 UTF-8转GBK 的问题。

失败经历:
失败1、String gbkline = new String(line.getBytes("GBK"));
失败2、String gbkline = new String(str.getBytes("utf-8"), "gbk")
失败3、

private static String utf8Togb2312(String str){
StringBuffer sb = new StringBuffer();
for(int i=0; i<str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case '+':
sb.append(' ');
break;
case '%':
try {
sb.append((char)Integer.parseInt(str.substring(i+1,i+3),16));
} catch (NumberFormatException e) {
throw new IllegalArgumentException();
}
i += 2;
break;
default:
sb.append(c);
break;
}
}
String result = sb.toString();
String res=null;
try {
byte[] inputBytes = result.getBytes("8859_1");
res= new String(inputBytes,"UTF-8");
}
catch(Exception e){}
return res;
}

失败4、

public static String utf82gbk(String utf) {
String l_temp = utf8ToUnicode(utf);
l_temp = Unicode2GBK(l_temp);

return l_temp;
}

/**
* utf-8 转unicode
*
* @param inStr
* @return String
*/
public static String utf8ToUnicode(String inStr) {
char[] myBuffer = inStr.toCharArray();

StringBuffer sb = new StringBuffer();
for (int i = 0; i < inStr.length(); i++) {
UnicodeBlock ub = UnicodeBlock.of(myBuffer[i]);
if (ub == UnicodeBlock.BASIC_LATIN) {
sb.append(myBuffer[i]);
} else if (ub == UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
int j = (int) myBuffer[i] - 65248;
sb.append((char) j);
} else {
short s = (short) myBuffer[i];
String hexS = Integer.toHexString(s);
String unicode = "\\u" + hexS;
sb.append(unicode.toLowerCase());
}
}
return sb.toString();
}

/**
*
* @param dataStr
* @return String
*/

public static String Unicode2GBK(String dataStr) {
int index = 0;
StringBuffer buffer = new StringBuffer();

int li_len = dataStr.length();
while (index < li_len) {
if (index >= li_len - 1
|| !"\\u".equals(dataStr.substring(index, index + 2))) {
buffer.append(dataStr.charAt(index));

index++;
continue;
}

String charStr = "";
charStr = dataStr.substring(index + 2, index + 6);

char letter = (char) Integer.parseInt(charStr, 16);

buffer.append(letter);
index += 6;
}

return buffer.toString();
}




我想应该有什么第三方插件,比如类似于 进制转换的。
http://www.blogjava.net/pengpenglin/archive/2010/02/22/313669.html
哪位兄台分享一下。在下感激不尽。
...全文
329 19 打赏 收藏 转发到动态 举报
写回复
用AI写文章
19 条回复
切换为时间正序
请发表友善的回复…
发表回复
周末来我家 2015-08-18
  • 打赏
  • 举报
回复
这个问题你要考虑到文件本身的编码,即便你内容显示的是utf-8,可能你的文件本身是别的编码比如ISO8859-1
gukuitian 2015-08-18
  • 打赏
  • 举报
回复
java程序内,编码类型只有在转换字节数组时才有意义 同一String在不同编码下,转换成的字节码是不同的, 对String来说,它本身是没有编码的概念的
gukuitian 2015-08-18
  • 打赏
  • 举报
回复
String gbkline=utf8ToGbk(line); 别的先不说,就看这一行就有问题 对java来说 永远不要考虑String的编码,它只有一种类型,谁也改不了.
nicholasbobo 2015-08-18
  • 打赏
  • 举报
回复
读取和写入文件都要设置对应的编码,比如你读的是GBK文件,那读的时候就要设置GBK编码,写入时按UTF-8写入,那写入的时候也要设置编码。 可以参考这篇文章http://blog.csdn.net/yaerfeng/article/details/19345597
大数据小白 2015-08-18
  • 打赏
  • 举报
回复
BufferedReader r = new BufferedReader(new InputStreamReader(is,"GBK")); name = r.readLine(); 楼主尝试修改下从缓存读取这个地方呢?
csdn01013 2015-08-13
  • 打赏
  • 举报
回复
package text; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Utf8ToGbk { public static void main(String[] args) { File file = new File("D:/b.txt"); File fileb = new File("D:/a.txt"); String line= ""; BufferedReader reader =null; OutputStreamWriter out = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileb),"UTF-8")); out = new OutputStreamWriter(new FileOutputStream(file)); while ((line=reader.readLine())!=null) { String gbkline=new String(line.getBytes("gbk"),"gbk"); out.write("\n"); out.write(gbkline);//gbk } } catch (IOException e1) { e1.printStackTrace(); } finally{ try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } 读取的是utf8,写入的gbk,你试过了?我在我电脑上运行通过
董小姐_123 2015-08-13
  • 打赏
  • 举报
回复
引用 10 楼 woshigaoshou980 的回复:
[quote=引用 8 楼 csdn01013 的回复:] package text; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Utf8ToGbk { public static void main(String[] args) { File file = new File("D:/b.txt"); File fileb = new File("D:/a.txt"); String line= ""; BufferedReader reader =null; OutputStreamWriter out = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileb),"UTF-8")); out = new OutputStreamWriter(new FileOutputStream(file)); while ((line=reader.readLine())!=null) { String gbkline=new String(line.getBytes("gbk"),"gbk"); out.write("\n"); out.write(gbkline);//gbk } } catch (IOException e1) { e1.printStackTrace(); } finally{ try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
你这个类似于 我的失败经历2,不行的。[/quote] 我用过这个,不知到又为什么不行
longbaopyl 2015-08-13
  • 打赏
  • 举报
回复
urlEncoding试下这个方法
frank7219 2015-08-12
  • 打赏
  • 举报
回复
private void changeEncoding(File sourceFile,File targetFile) throws IOException {
		FileInputStream fin = null;
		
		FileOutputStream fout= null;
		FileChannel fcin = null;
		FileChannel fcout = null;
		if (targetEncoding == null) {
			this.targetEncoding = System.getProperty("file.encoding");
		}
		try {
			fin = new FileInputStream(sourceFile);
			fout = new FileOutputStream(targetFile);
			fcin = fin.getChannel();
			fcout = fout.getChannel();
			
			ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
			while(true){
				buffer.clear();
				int r = fcin.read(buffer);
				if (r == -1) break;
				buffer.flip();
				
				byte[] bys = Charset.forName(sourceEncoding).decode(buffer)
						.toString().getBytes(targetEncoding);
				
				fcout.write(buffer.wrap(bys));
			}
			
		} catch (Exception e) {
		} finally {
			if (fin != null) {
				fin.close();
			}
			if (fcin != null) {
				fcin.close();
			}
			if (fout != null) {
				fout.close();
			}
			if (fcout != null) {
				fcout.close();
			}
		}
		
	}
  • 打赏
  • 举报
回复
引用 8 楼 csdn01013 的回复:
package text; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Utf8ToGbk { public static void main(String[] args) { File file = new File("D:/b.txt"); File fileb = new File("D:/a.txt"); String line= ""; BufferedReader reader =null; OutputStreamWriter out = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileb),"UTF-8")); out = new OutputStreamWriter(new FileOutputStream(file)); while ((line=reader.readLine())!=null) { String gbkline=new String(line.getBytes("gbk"),"gbk"); out.write("\n"); out.write(gbkline);//gbk } } catch (IOException e1) { e1.printStackTrace(); } finally{ try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
你这个类似于 我的失败经历2,不行的。
  • 打赏
  • 举报
回复
哈哈,我试了下,设置2个文件,b为utf-8,a为gbk, 我utf-8取,GBK存,不行 utf-8取,utf-8存,也不行,哈哈 我设断点看了下,读出来的时候就乱码了,你看看你的
csdn01013 2015-08-12
  • 打赏
  • 举报
回复
package text; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Utf8ToGbk { public static void main(String[] args) { File file = new File("D:/b.txt"); File fileb = new File("D:/a.txt"); String line= ""; BufferedReader reader =null; OutputStreamWriter out = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileb),"UTF-8")); out = new OutputStreamWriter(new FileOutputStream(file)); while ((line=reader.readLine())!=null) { String gbkline=new String(line.getBytes("gbk"),"gbk"); out.write("\n"); out.write(gbkline);//gbk } } catch (IOException e1) { e1.printStackTrace(); } finally{ try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
  • 打赏
  • 举报
回复
引用 6 楼 woshigaoshou980 的回复:
你把我代码复制下来跑一边就知道了。你会发现UTF8的txt写入到GBK的txt以后,用GBK模式打开a.txt内容不对。
哎...好吧,我试试
  • 打赏
  • 举报
回复
引用 4 楼 shijing266 的回复:
[quote=引用 3 楼 woshigaoshou980 的回复:] 你那样不行,你这样就跟我上面失败经历4一样,先utf8 转 Unicode ,然后Unicode转gbk。 不行了,试过了。
按道理不会啊,你能知道双方用什么编码,用utf-8取出来,gbk存进去按道理没问题啊[/quote] 你把我代码复制下来跑一边就知道了。你会发现UTF8的txt写入到GBK的txt以后,用GBK模式打开a.txt内容不对。
  • 打赏
  • 举报
回复
引用 2 楼 rui888 的回复:
http://stackoverflow.com/questions/22898022/how-to-convert-utf-8-to-gbk-string-in-java
我这边公司屏蔽外网, stackoverflow根本访问不了
  • 打赏
  • 举报
回复
引用 3 楼 woshigaoshou980 的回复:
你那样不行,你这样就跟我上面失败经历4一样,先utf8 转 Unicode ,然后Unicode转gbk。 不行了,试过了。
按道理不会啊,你能知道双方用什么编码,用utf-8取出来,gbk存进去按道理没问题啊
  • 打赏
  • 举报
回复
引用 1 楼 shijing266 的回复:
String utf8 = new String(t.getBytes( "UTF-8"));  
System.out.println(utf8);  
String unicode = new String(utf8.getBytes(),"UTF-8");   
System.out.println(unicode);  
String gbk = new String(unicode.getBytes("GBK"));  
  
System.out.println(gbk);  
这样呢?
你那样不行,你这样就跟我上面失败经历4一样,先utf8 转 Unicode ,然后Unicode转gbk。 不行了,试过了。
tony4geek 2015-08-12
  • 打赏
  • 举报
回复
http://stackoverflow.com/questions/22898022/how-to-convert-utf-8-to-gbk-string-in-java
  • 打赏
  • 举报
回复
String utf8 = new String(t.getBytes( "UTF-8"));  
System.out.println(utf8);  
String unicode = new String(utf8.getBytes(),"UTF-8");   
System.out.println(unicode);  
String gbk = new String(unicode.getBytes("GBK"));  
  
System.out.println(gbk);  
这样呢?

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧