二进制文件与字符串互转代码

因为在传送音频文件的时候使用的开源包有bug...不得已使用通过消息传输的方式来传输文件,思路是先将文件转成16进制格式的字符串,经消息通道传送后还原成文件。示例代码如下:

//调用举例
public static void main(String[] args) {

String sFileContent;
sFileContent=fileToHexString(new File("c://原始文件.dat"));

System.out.println("文件内容:"+sFileContent);

hexStringToFile(sFileContent,new File("c://还原文件.dat"));

}

// 文件转成16进制字符串
private static String fileToHexString(File file) {

try {
DataInputStream din = new DataInputStream(new FileInputStream(file));
StringBuilder hexData = new StringBuilder();
byte temp = 0;
for (int i = 0; i < file.length(); i++) {

temp = din.readByte();

// 以十六进制的无符号整数形式返回一个字符串表示形式。
String str = Integer.toHexString(temp);

if (str.length() ==8) {// 去掉补位的f
str = str.substring(6);
}
if (str.length() == 1) {
str = "0" + str;
}
hexData.append(str.toUpperCase());
}

din.close();

return hexData.toString();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

// 16进制字符串转成文件
private static void hexStringToFile(String sHex,File file) {

try {
BufferedOutputStream bof=new BufferedOutputStream(new FileOutputStream(file));
bof.write(hexStr2Bytes(sHex));
bof.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

//辅助hexStr2Bytes()
private static byte uniteBytes(String src0, String src1) {
byte b0 = Byte.decode("0x" + src0).byteValue();
b0 = (byte) (b0 << 4);
byte b1 = Byte.decode("0x" + src1).byteValue();
byte ret = (byte) (b0 | b1);
return ret;
}

//bytes转换成十六进制字符串,辅助hexStringToFile()
public static byte[] hexStr2Bytes(String src) {
int m=0,n=0;
int l=src.length()/2;
//System.out.println(l);
byte[] ret = new byte[l];
for (int i = 0; i < l; i++) {
m=i*2+1;
n=m+1;
ret[i] = uniteBytes(src.substring(i*2, m),src.substring(m,n));
}
return ret;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值