文件,byte[],HexString 之间的转换
- 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;
- }