charset java getbyte_java String.getBytes()编码问题——String.getBytes(charset)

String的getBytes()方法是得到一个字串的字节数组,这是众所周知的。但特别要注意的是,本方法将返回该操作系统默认的编码格式的字节数组。如果你在使用这个方法时不考虑到这一点,你会发现在一个平台上运行良好的系统,放到另外一台机器后会产生意想不到的问题。比如下面的程序:

class TestCharset {

public static void main(String[] args) {

new TestCharset().execute();

}

private void execute() {

String s = "Hello!你好!";

byte[] bytes = s.getBytes();

System.out.println("bytes lenght is:" + bytes.length);

}

}

在一个中文WindowsXP系统下,运行时,结果为:

bytes lenght is:12

但是如果放到了一个英文的UNIX环境下运行:

$ java TestCharset bytes lenght is:9

如果你的程序依赖于该结果,将在后续操作中引起问题。为什么在一个系统中结果为12,而在另外一个却变成了9了呢?上面已经提到了,该方法是和平台(编码)相关的。

在中文操作系统中,getBytes方法返回的是一个GBK或者GB2312的中文编码的字节数组,其中中文字符,各占两个字节。而在英文平台中,一般的默认编码是“ISO-8859-1”,每个字符都只取一个字节(而不管是否非拉丁字符)。

Java中的编码支持

Java是支持多国编码的,在Java中,字符都是以Unicode进行存储的,比如,“你”字的Unicode编码是“4f60”,我们可以通过下面的实验代码来验证:

class TestCharset {

public static void main(String[] args) {

char c = '你';

int i = c;

System.out.println(c);

System.out.println(i);

}

}

不管你在任何平台上执行,都会有相同的输出:

20320

20320就是Unicode “4f60”的整数值。其实,你可以反编译上面的类,可以发现在生成的.class文件中字符“你”(或者其它任何中文字串)本身就是以Unicode编码进行存储的:

char c = '/u4F60'; ... ...

即使你知道了编码的编码格式,比如:

javac -encoding GBK TestCharset.java

编译后生成的.class文件中仍然是以Unicode格式存储中文字符或字符串的。使用String.getBytes(String charset)方法

所以,为了避免这种问题,我建议大家都在编码中使用String.getBytes(String charset)方法。下面我们将从字串分别提取ISO-8859-1和GBK两种编码格式的字节数组,看看会有什么结果:

packageorg.bruce.file.handle.experiment;classTestCharset3 {public static voidmain(String[] args) {newTestCharset3().execute();

}private voidexecute() {

String s= "Hello!你好!";byte[] bytesISO8859 = null;byte[] bytesGBK = null;try{

bytesISO8859= s.getBytes("iso-8859-1");

bytesGBK= s.getBytes("GBK");

}catch(java.io.UnsupportedEncodingException e) {

e.printStackTrace();

}

System.out.println("-------------- /n 8859 bytes:");

System.out.println("bytes is: " +arrayToString(bytesISO8859));

System.out.println("hex format is:" +encodeHex(bytesISO8859));

System.out.println();

System.out.println("-------------- /n GBK bytes:");

System.out.println("bytes is: " +arrayToString(bytesGBK));

System.out.println("hex format is:" +encodeHex(bytesGBK));

}public static final String encodeHex(byte[] bytes) {

StringBuffer buff= new StringBuffer(bytes.length * 2);

String b;for (int i = 0; i < bytes.length; i++) {

b=Integer.toHexString(bytes[i]);//byte是两个字节的, 而上面的Integer.toHexString会把字节扩展为4个字节

buff.append(b.length() > 2 ? b.substring(6, 8) : b);

buff.append(" ");

}returnbuff.toString();

}public static final String arrayToString(byte[] bytes) {

StringBuffer buff= newStringBuffer();for (int i = 0; i < bytes.length; i++) {

buff.append(bytes[i]+ " ");

}returnbuff.toString();

}

}

执行上面程序将打印出:

-------------- 8859 bytes: bytes is: 72 101 108 108 111 33 63 63 63

hex format is:48 65 6c 6c 6f 213f 3f 3f

--------------  GBK bytes: bytes is: 72 101 108 108 111 33 -60 -29 -70 -61 -93 -95

hex format is:48 65 6c 6c 6f 21 c4 e3 ba c3 a3 a1

可见,在s中提取的8859-1格式的字节数组长度为9,中文字符都变成了“63”,ASCII码为63的是“?”,一些国外的程序在国内中文环境下运行时,经常出现乱码,上面布满了“?”,就是因为编码没有进行正确处理的结果。

而提取的GBK编码的字节数组中正确得到了中文字符的GBK编码。字符“你”“好”“!”的GBK编码分别是:“c4e3”“bac3”“a3a1”。得到了正确的以GBK编码的字节数组,以后需要还原为中文字串时,可以使用下面方法:

new String(byte[] bytes, String charset)

mysql 不支持 unicode,所以比较麻烦。

将 connectionString 设置成 encoding 为 gb2312

String connectionString

= "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=gb2312";

测试代码:

String str = "汉字";

PreparedStatement pStmt = conn.prepareStatement("INSERT INTO test VALUES (?)");

pStmt.setString(1,str);

pStmt.executeUpdate();

数据库表格:

create table test (

name char(10)

)

连接 Oracle Database Server

-------------------------------------------------------------------------------

在把汉字字符串插入数据库前做如下转换操作:

String(str.getBytes("ISO8859_1"),"gb2312")

测试代码:

String str = "汉字";

PreparedStatement pStmt = conn.prepareStatement("INSERT INTO test VALUES (?)");

pStmt.setString(1,new String(str.getBytes("ISO8859_1"),"gb2312");

pStmt.executeUpdate();

Servlet

-------------------------------------------------------------------------------

在 Servlet 开头加上两句话:

response.setContentType("text/html;charset=UTF-8");

request.setCharacterEncoding("UTF-8");

JSP

-------------------------------------------------------------------------------

1 @Test2 public voidtestBytes(){3 //字节数4 //中文:ISO:1 GBK:2 UTF-8:35 //数字或字母: ISO:1 GBK:1 UTF-8:1

6 String username = "中";7 try{8 //得到指定编码的字节数组 字符串--->字节数组

9 byte[] u_iso=username.getBytes("ISO8859-1");10 byte[] u_gbk=username.getBytes("GBK");11 byte[] u_utf8=username.getBytes("utf-8");12 System.out.println(u_iso.length);13 System.out.println(u_gbk.length);14 System.out.println(u_utf8.length);15 //跟上面刚好是逆向的,字节数组---->字符串

16 String un_iso=new String(u_iso, "ISO8859-1");17 String un_gbk=new String(u_gbk, "GBK");18 String un_utf8=new String(u_utf8, "utf-8");19 System.out.println(un_iso);20 System.out.println(un_gbk);21 System.out.println(un_utf8);22 //有时候必须是iso字符编码类型,那处理方式如下

23 String un_utf8_iso=new String(u_utf8, "ISO8859-1");24 //将iso编码的字符串进行还原

25 String un_iso_utf8=new String(un_utf8_iso.getBytes("ISO8859-1"),"UTF-8");26 System.out.println(un_iso_utf8);27

28 } catch(UnsupportedEncodingException e) {29 //TODO Auto-generated catch block

30 e.printStackTrace();31 }32 }

测试结果:

1

2

3

?

中

从转载的文章摘:

乱码原因:为什么使用ISO8859-1编码再组合之后,无法还原"中"字呢,其实原因很简单,因为ISO8859-1编码的编码表中,根本就没有包含汉字字符,当然也就无法通过"中".getBytes("ISO8859-1");来得到正确的"中"字在ISO8859-1中的编码值了,所以再通过new String()来还原就无从谈起了.

有时候,为了让中文字符适应某些特殊要求(如http header头要求其内容必须为iso8859-1编码),可能会通过将中文字符按照字节方式来编码的情况,如:

String s_iso88591 = new String("中".getBytes("UTF-8"),"ISO8859-1"),这样得到的s_iso8859-1字符串实际是三个在ISO8859-1中的字符,在将这些字符传递到目的地后,目的地程序再通过相反的方式String s_utf8 = new String(s_iso88591.getBytes("ISO8859-1"),"UTF-8")来得到正确的中文汉字"中".这样就既保证了遵守协议规定、也支持中文.

转自:http://blog.csdn.net/yang3wei/article/details/7381578          http://blog.csdn.net/techbirds_bao/article/details/8555449

package com.youlai.system.model.algori.controller; import com.sun.jna.Memory; import com.sun.jna.Pointer; import com.youlai.system.model.algori.STFT; import com.youlai.system.model.algori.entity.STFTResult; import org.springframework.web.bind.annotation.*; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.Arrays; /** * STFT音频处理控制器 * 提供RESTful API接口实现音频分析功能 */ @RestController @RequestMapping("/api/stft") public class STFTController { static { try { System.out.println("JVM架构: " + System.getProperty("sun.arch.data.model") + "位"); System.setProperty("java.library.path", "src/main/resources/lib"); System.out.println("库路径: " + System.getProperty("java.library.path")); } catch (Exception e) { System.err.println("库路径配置失败: " + e.getMessage()); } } // 注入STFT库实例 private final STFT stftLibary = STFT.getInstance(); /** * 计算短时傅里叶变换 * @param filepath 音频文件路径(默认值:1-1.csv) * @param frameSize 帧长(默认值:256) * @param frameShift 帧移(默认值:128) * @param sampleRate 采样率(默认值:400.0) * @param windowType 窗类型(默认值:0) * @return 计算结果指针 */ @GetMapping("/compute") public String computeSTFT( @RequestParam(name = "filepath", defaultValue = "src/main/resources/1-1.csv") String filepath, @RequestParam(name = "frame_size", defaultValue = "256") int frameSize, @RequestParam(name = "frame_shift", defaultValue = "128") int frameShift, @RequestParam(name = "sample_rate", defaultValue = "400.0") double sampleRate, @RequestParam(name = "window_type", defaultValue = "0") int windowType) { // 添加文件路径验证 File file = new File(filepath); if (!file.exists()) { System.err.println("文件不存在: " + file.getAbsolutePath()); return "计算失败: 文件不存在"; } if (!file.canRead()) { System.err.println("无读取权限: " + file.getAbsolutePath()); return "计算失败: 无文件读取权限"; } // 添加编码验证 if (!filepath.equals(new String(filepath.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8))) { System.err.println("文件路径包含非UTF-8字符: " + filepath); return "计算失败: 文件路径包含非法字符"; } long resultPtr = 0; try { // 调用本地方法计算STFT resultPtr = stftLibary.compute_stft( filepath, frameSize, frameShift, sampleRate, windowType ); Pointer ptr = Memory.createConstant(resultPtr); if(ptr == null) return "计算失败,结果为空"; else if(ptr.getByte(0) == 0) return "计算失败,无法访问"; if (resultPtr == 0) { return "计算失败,结果为空"; } } catch (Exception e) { // 异常处理 System.err.println("STFT计算异常: " + e.getMessage()); e.printStackTrace(); return "计算失败: " + e.getMessage(); }finally { stftLibary.freeResult(resultPtr); } return "计算成功"; } }为什么获取到的ptr是一个opaque指针
07-25
Java 中使用 `ByteBuf` 的 `getBytes()` 方法遍历并打印字节十六进制表示时出现报错,可能有多种原因,以下是常见问题及解决办法: ### 1. `ByteBuf` 未正确初始化 如果 `ByteBuf` 未正确初始化,调用 `getBytes()` 方法可能会引发异常。确保 `ByteBuf` 被正确分配内存并写入数据。 ```java import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; public class ByteBufExample { public static void main(String[] args) { // 正确初始化 ByteBuf 并写入数据 ByteBuf byteBuf = Unpooled.buffer(10); byteBuf.writeBytes("Hello".getBytes()); // 遍历并打印字节的十六进制表示 for (int i = 0; i < byteBuf.readableBytes(); i++) { byte b = byteBuf.getByte(i); System.out.printf("%02X ", b); } byteBuf.release(); } } ``` ### 2. `ByteBuf` 已被释放 如果 `ByteBuf` 已经被释放,再调用 `getBytes()` 方法会抛出异常。确保在使用 `ByteBuf` 期间没有意外释放它,并且在使用完毕后再进行释放操作。 ```java import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; public class ByteBufReleaseExample { public static void main(String[] args) { ByteBuf byteBuf = Unpooled.buffer(10); byteBuf.writeBytes("Hello".getBytes()); // 错误示例:提前释放 ByteBuf // byteBuf.release(); // 遍历并打印字节的十六进制表示 for (int i = 0; i < byteBuf.readableBytes(); i++) { byte b = byteBuf.getByte(i); System.out.printf("%02X ", b); } // 使用完毕后释放 ByteBuf byteBuf.release(); } } ``` ### 3. 索引越界问题 在使用 `getBytes()` 方法时,如果索引超出了 `ByteBuf` 的可读字节范围,会抛出 `IndexOutOfBoundsException`。确保索引在合法范围内。 ```java import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; public class ByteBufIndexExample { public static void main(String[] args) { ByteBuf byteBuf = Unpooled.buffer(10); byteBuf.writeBytes("Hello".getBytes()); // 正确遍历:确保索引在可读字节范围内 for (int i = 0; i < byteBuf.readableBytes(); i++) { byte b = byteBuf.getByte(i); System.out.printf("%02X ", b); } byteBuf.release(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值