java字符集与编码问题

没想到自己的第一篇javaeye博客就是让人头痛的java字符集转码问题,下面是我个人的一些认识与网上收集的代码。在java中String在JVM里是unicode的,任何byte[]到String以及String到byte[]都涉及到字符集编码转换。基本规则是:

从byte[] 到String就是按某一个编码后的字节数组转换为unicode的字符串,从String到 byte[]是将unicode的字符串编码为唯一特定字符集编码后的字节数组。也就是说,Java编译时候,会将java文件的编码按照指定编码或者系统默认的编码转换为Unicode并加载到内存中进行编译。

public String(byte[] bytes)

这个方法就是完成将bytes[]转码为unicode的String。

使用的是jvm默认的字符集编码。

如果用户指定某一个charsetName,可以是UTF-8,GBK之类的。

public String(byte[] bytes, String charsetName)

两者都是完成specCharset到unicode的过程,而不是说改变编码格式为charsetName指定的字符集编码

同理

public byte[] getBytes()

public byte[] getBytes(String charsetName)

这两个方法就是完成从unicode到指定字符集编码的“转码”过程。

在浏览器中,http请求的parameter到servlet里后,应用服务器已经自动完成了new String(parameterBytes,browserSpecCharset)这个过程。

即,自动用页面设置的charset转码parameterBytes字节数组为unicode的字符串。

下面是网上找的一个转码器的例子,经测试比较好用,大家可以自己试试

package lavasoft.common;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import java.io.*;

/**

* 转码工具,全面支持文件、字符串的转码

*

* @author Administrator 2009-11-29 16:14:21

*/

public class EncodingToolkit {

private static Log log = LogFactory.getLog(EncodingToolkit.class);

public static void main(String[] args) {

String han = "汉";

System.out.println("---------");

}

/**

* 对字符串重新编码

*

* @param text 字符串

* @param resEncoding 源编码

* @param newEncoding 新编码

* @return 重新编码后的字符串

*/

public static String reEncoding(String text, String resEncoding, String newEncoding) {

String rs = null;

try {

rs = new String(text.getBytes(resEncoding), newEncoding);

} catch (UnsupportedEncodingException e) {

log.error("读取文件为一个内存字符串失败,失败原因是使用了不支持的字符编码");

throw new RuntimeException(e);

}

return rs;

}

/**

* 重新编码Unicode字符串

*

* @param text 源字符串

* @param newEncoding 新的编码

* @return 指定编码的字符串

*/

public static String reEncoding(String text, String newEncoding) {

String rs = null;

try {

rs = new String(text.getBytes(), newEncoding);

} catch (UnsupportedEncodingException e) {

log.error("读取文件为一个内存字符串失败,失败原因是使用了不支持的字符编码" + newEncoding);

throw new RuntimeException(e);

}

return rs;

}

/**

* 文本文件重新编码

*

* @param resFile 源文件

* @param resEncoding 源文件编码

* @param distFile 目标文件

* @param newEncoding 目标文件编码

* @return 转码成功时候返回ture,否则false

*/

public static boolean reEncoding(File resFile, String resEncoding, File distFile, String newEncoding) {

boolean flag = true;

InputStreamReader reader = null;

OutputStreamWriter writer = null;

try {

reader = new InputStreamReader(new FileInputStream(resFile), resEncoding);

writer = new OutputStreamWriter(new FileOutputStream(distFile), newEncoding);

char buf[] = new char[1024 * 64]; //字符缓冲区

int len;

while ((len = reader.read(buf)) != -1) {

writer.write(buf, 0, len);

}

writer.flush();

writer.close();

reader.close();

} catch (FileNotFoundException e) {

flag = false;

log.error("没有找到文件,转码发生异常!");

throw new RuntimeException(e);

} catch (IOException e) {

flag = false;

log.error("读取文件为一个内存字符串失败,失败原因是读取文件异常!");

throw new RuntimeException(e);

} finally {

if (reader != null) try {

reader.close();

} catch (IOException e) {

flag = false;

throw new RuntimeException(e);

} finally {

if (writer != null) try {

writer.close();

} catch (IOException e) {

flag = false;

throw new RuntimeException(e);

}

}

}

return flag;

}

/**

* 读取文件为一个Unicode编码的内存字符串,保持文件原有的换行格式

*

* @param resFile 源文件对象

* @param encoding 文件字符集编码

* @return 文件内容的Unicode字符串

*/

public static String file2String(File resFile, String encoding) {

StringBuffer sb = new StringBuffer();

try {

LineNumberReader reader = new LineNumberReader(new BufferedReader(new InputStreamReader(new FileInputStream(resFile), encoding)));

String line;

while ((line = reader.readLine()) != null) {

sb.append(line).append(System.getProperty("line.separator"));

}

reader.close();

} catch (UnsupportedEncodingException e) {

log.error("读取文件为一个内存字符串失败,失败原因是使用了不支持的字符编码" + encoding);

throw new RuntimeException(e);

} catch (FileNotFoundException e) {

log.error("读取文件为一个内存字符串失败,失败原因所给的文件" + resFile + "不存在!");

throw new RuntimeException(e);

} catch (IOException e) {

log.error("读取文件为一个内存字符串失败,失败原因是读取文件异常!");

throw new RuntimeException(e);

}

return sb.toString();

}

/**

* 使用指定编码读取输入流为一个内存Unicode字符串,保持文件原有的换行格式

*

* @param in 输入流

* @param encoding 构建字符流时候使用的字符编码

* @return Unicode字符串

*/

public static String stream2String(InputStream in, String encoding) {

StringBuffer sb = new StringBuffer();

LineNumberReader reader = null;

try {

reader = new LineNumberReader(new BufferedReader(new InputStreamReader(in, encoding)));

String line;

while ((line = reader.readLine()) != null) {

sb.append(line).append(System.getProperty("line.separator"));

}

reader.close();

in.close();

} catch (UnsupportedEncodingException e) {

log.error("读取文件为一个内存字符串失败,失败原因是使用了不支持的字符编码" + encoding);

throw new RuntimeException(e);

} catch (IOException e) {

log.error("读取文件为一个内存字符串失败,失败原因是读取文件异常!");

throw new RuntimeException(e);

} finally {

if (in != null) try {

in.close();

} catch (IOException e) {

log.error("关闭输入流发生异常!", e);

throw new RuntimeException(e);

}

}

return sb.toString();

}

/**

* 字符串保存为制定编码的文本文件

*

* @param text 字符串

* @param distFile 目标文件

* @param encoding 目标文件的编码

* @return 转换成功时候返回ture,否则false

*/

public static boolean string2TextFile(String text, File distFile, String encoding) {

boolean flag = true;

if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs();

OutputStreamWriter writer = null;

try {

writer = new OutputStreamWriter(new FileOutputStream(distFile), encoding);

writer.write(text);

writer.close();

} catch (IOException e) {

flag = false;

log.error("将字符串写入文件发生异常!");

throw new RuntimeException(e);

} finally {

if (writer != null) try {

writer.close();

} catch (IOException e) {

log.error("关闭输出流发生异常!", e);

throw new RuntimeException(e);

}

}

return flag;

}

}

1 楼

jyjava

2011-12-29

流为啥要关闭两次

java字符集编码是,java字符集与编码有关问题相关推荐

  1. java 获得系统字符集_Java - 获取系统字符集编码

    名词解释 ASCII(American Standard Code for Information Interchange,美国信息互换标准代码) 基于常用英文字符 计算机处理时都是以二进制码的形式出 ...

  2. 字符集与字符编码,java中的char和unicode

    文章目录 基本单位转换 进制缩写与表示 字符.字符集.字符编码 ASCII码 全角 GBK.GB2312 为什么需要字符编码 UTF-8和Unicode的关系 java中的char 和unicode ...

  3. java所使用的字符集是_Java常用字符集编码详解

    Java常用字符集编码详解 Web开发的时候经常会遇到一些字符编码的错误,如页面乱码等问题,所以有必要需对字符编码有所了解,以下是Ricki收集的一些资料(可能不是很全,但希望对你有所帮助) Java ...

  4. Java中的字符集编码入门Java中的增补字符

    转载自:http://jiangzhengjun.iteye.com/blog/512083 Java中的字符集编码入门Java中的增补字符 博客分类: 字符集编码 Java Java号称对Unico ...

  5. java encode in ansi_Java应用中的编码问题

    1. 概述 本文主要包括以下几个方面:编码基本知识,java,系统软件,url,工具软件等. 在下面的描述中,将以"中文"两个字为例,经查表可以知道其GB2312编码是" ...

  6. html ascii编码方式,HTML 字符集 参考手册

    要正确显示一个 HTML 页面,浏览器必须知道要使用的字符集(字符编码). HTML 字符集 在 HTML 中,正确的字符编码是什么? HTML5 中默认的字符编码是 UTF-8. 这并非总是如此.早 ...

  7. java中几种常见字符集与乱码介绍

    1.  ASCII和Ansi编码 字符内码(charcter code)指的是用来代表字符的内码 .读者在输入和存储文档时都要使用内码,内码分为  单字节内码 -- Single-Byte chara ...

  8. Java在编译到执行过程的编码问题

    一.两个字符编码的参数 javac和java是JDK自带的工具,其中javac是编译工具,java工具启动Java虚拟机并执行java程序.这两个工具都带有设置字符编码的选项.本文讨论字符编码选项的使 ...

  9. java string设置编码_详解Java中String类型与默认字符编码

    为什么写这个 至于为什么要写这个,主要是一句mmp一定要讲,绕了一上午,晕死 Java程序中的中文乱码问题一直是一个困扰程序员的难题,自己也不例外,早在做项目时就遇到过很多编码方式的坑,当时想填来着, ...

最新文章

  1. 数学知识--Levenberg-Marquardt算法浅谈
  2. PHP curl 实现RESTful PUT DELETE 实例
  3. Android开发--初探SQLiteDataBase/数据库的创建,更新,插入,查询
  4. 云计算市场竞争激烈 亚马逊微软IBM阿里业绩亮眼
  5. MongoDB如何一次插入多条json数据--转
  6. Leecode11. 盛最多水的容器——Leecode大厂热题100道系列
  7. Windows Server 2016及System Center 2016正式商用
  8. php mysql 秒杀_redis+PHP实现高并发下秒杀数据入库的问题
  9. Ajax请求成功后页面跳转
  10. 首页大广告 redis缓存
  11. mqtt之C++编译
  12. 硬件防火墙销售 Apache 遭遇DDOS攻击!!!!!!!!!!
  13. 从周易六十四卦看软件架构真好懂!女朋友这下不用担心我的学习了【程序员编程】
  14. 接口测试用例设计:常见问题和风险
  15. 最全PLC输入输出各种回路接线
  16. c++ linux utf-8 编码 中文汉字分割(超简单代码)
  17. VMware Vsphere-下
  18. VMware 12 Exception 0xc0000005
  19. JAVA做语言国际化
  20. accountmanager 调用说明

热门文章

  1. android java 实体类 object变量 保存_Android中Intent传递对象的两种方法Serializable,Parcelable...
  2. java并发问题_并发理论基础:并发问题产生的三大根源
  3. python爬取ajax动态内容肯德基门店,Python爬虫如何爬取KFC地址
  4. 验证码识别Burp reCAPTCHA插件使用
  5. linux基于域名的虚拟主机,Nginx虚拟主机应用——基于域名、IP、端口的虚拟主机...
  6. java 文件缓冲区_Java开发笔记(八十六)通过缓冲区读写文件
  7. php最常用方法,php 常用方法
  8. CSS3与页面布局学习笔记(二)——盒子模型(Box Model)、边距折叠、内联与块标签、CSSReset
  9. 基于python语言下的UI自动化测试框架搭建(四)
  10. CSS基础学习-15-1.CSS 浏览器内核