如何有效地将字节数组转换为字符串
我有一个151字节的字节数组,通常是一个记录,记录需要插入到oracle数据库中。 在151字节的数组范围内,从0到1是记录id,2到3是引用id,4到9是日期值。 字节数组中的以下数据是日期值。 我想将其转换为字符串
byte[] b= {48,48,49,48,48,52}; // when converted to string it becomes 10042. new String(b); // current approach
有没有办法有效地将某些范围的字节数组( Arrays.copyOfRange(b,0,5)
)转换为字符串。
new String(b, 0 ,5);
Gee,谁能猜到? 每个人都费心去看API文档 ,那就是谁。
使用String(bytes[] bytes, int offset, int length)
构造函数:http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#String(byte [] ,int,int)
new String(b, 0, 5);
如果你需要为记录中的每个区域创建一个字符串,我建议使用子字符串方法:
byte[] wholeRecord = {0,1,2 .. all record goes here .. 151} String wholeString = new String(wholeRecord); String id = wholeString.substring(0,1); String refId = wholeString.substring(1,3); ...
根据字符串编码,实际偏移可能不同。
这种方法的优点是字节数组只复制一次。 对substring()
后续调用不会创建副本,但只会引用带偏移的第一个副本。 因此,您可以节省一些内存和arrays复制时间。
这里很棒的方式(效率不高):)
byte[] b = { 48, 48, 49, 48, 48, 52 }; ByteArrayInputStream bais = new ByteArrayInputStream(b); BufferedReader buf = new BufferedReader(new InputStreamReader(bais)); String s = buf.readLine(); System.out.println(s);
这里没有任何答案认为您可能没有使用ASCII。 将字节转换为字符串时,应始终考虑字符集。
new String(bytes, offset, length, charset);
- 如何在调试模式下运行时修改java代码?
- Java API中的循环计数器
- 为什么线程会自动从wait()中唤醒?
- 为什么\ n和(String)System.getProperty(“line.separator”); 行为不同?
- 如何使用DaoAuthenticationProvider以编程方式使用Spring Security对用户进行身份validation
- 当CompleteableFuture抛出exception时返回500内部错误
- 如何在Apache HTTP Client 4中使用Socks 5代理?
- 在eclipse氧气版本中选择Java 9中的JRE运行时环境
- 如何在Java Filter中更改HTTP响应内容长度标头