字符串 二进制数字 转换 java_如何将二进制数据转换为字符串并返回到Java中?

String(byte[])

将数据视为默认字符编码。因此,如何将字节从8位值转换为16位Java Unicode字符将不仅在操作系统之间发生变化,而且甚至可以在同一台机器上使用不同代码页的不同用户之间变化。此构造函数只适用于解码您自己的文本文件之一。不要尝试将任意字节转换为字符爪哇!

编码为

base64

是一个很好的解决方案。这是通过SMTP(电子邮件)发送文件的方式。(免费)阿帕奇

Commons Codec

项目将完成这项工作。

byte[] bytes = loadFile(file);

//all chars in encoded are guaranteed to be 7-bit ASCII

byte[] encoded = Base64.encodeBase64(bytes);

String printMe = new String(encoded, "US-ASCII");

System.out.println(printMe);

byte[] decoded = Base64.decodeBase64(encoded);

import java.io.*;

import java.nio.channels.*;

import javax.xml.bind.DatatypeConverter;

public class EncodeDecode {

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

File file = new File("/bin/ls");

byte[] bytes = loadFile(file, new ByteArrayOutputStream()).toByteArray();

String encoded = DatatypeConverter.printBase64Binary(bytes);

System.out.println(encoded);

byte[] decoded = DatatypeConverter.parseBase64Binary(encoded);

// check

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

assert bytes[i] == decoded[i];

}

}

private static T loadFile(File file, T out)

throws IOException {

FileChannel in = new FileInputStream(file).getChannel();

try {

assert in.size() == in.transferTo(0, in.size(), Channels.newChannel(out));

return out;

} finally {

in.close();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值