import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
*
* 文件,byte[],HexString 之间的转换
*
*/
public class FileDataConvert {
public static void main(String[] args) {
String srcFilePath = "d:/testFrom.png";
String outFilePath = "d:/";
String outFileName = "testTo.png";
byte[] bytes = getBytesFromFile(srcFilePath);
String str = bytes2HexString(bytes);
System.out.println(str);
byte[] bytes2 = hexString2Bytes(str);
saveBytes2File(bytes2, outFilePath, outFileName);
}
/**
* 从文件中获取byte数组
*/
public static byte[] getBytesFromFile(String filePath) {
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
/**
* 根据byte数组生成文件
*/
public static void saveBytes2File(byte[] bfile, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {
dir.mkdirs();
}
file = new File(filePath + "\\" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
/**
* 从字节数组到十六进制字符串转换
*/
public static String bytes2HexString(byte[] b) {
byte[] buff = new byte[2 * b.length];
for (int i = 0; i < b.length; i++) {
buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
buff[2 * i + 1] = hex[b[i] & 0x0f];
}
return new String(buff);
}
/**
* 从十六进制字符串到字节数组转换
*/
public static byte[] hexString2Bytes(String hexstr) {
byte[] b = new byte[hexstr.length() / 2];
int j = 0;
for (int i = 0; i < b.length; i++) {
char c0 = hexstr.charAt(j++);
char c1 = hexstr.charAt(j++);
b[i] = (byte) ((parse(c0) << 4) | parse(c1));
}
return b;
}
private final static byte[] hex = "0123456789ABCDEF".getBytes();
private static int parse(char c) {
if (c >= 'a')
return (c - 'a' + 10) & 0x0f;
if (c >= 'A')
return (c - 'A' + 10) & 0x0f;
return (c - '0') & 0x0f;
}
}
文件,byte[],HexString 之间的转换
最新推荐文章于 2024-04-03 17:00:18 发布
本文提供了一个Java程序示例,演示了如何将文件内容转换为字节数组,将其转换为十六进制字符串,并最终将转换后的字节数组保存回文件。该程序使用了Java I/O流的相关类,包括FileInputStream、FileOutputStream、ByteArrayOutputStream和BufferedOutputStream。
2350

被折叠的 条评论
为什么被折叠?



