最近在搞文件升级 遇到 16进制转为文件,然后文件转为16进制
下面为代码:
1 import java.io.*;
2
3 /**
4 * @author ipodao@qq.com
5 * @date 2019/9/4 16:05
6 */
7 public class ExportFile {
8 private static final String EXPORT_PATH = "C:\\Users\\ipodao\\OneDrive\\文档\\rowan\\1\\";
9
10 public static void main(String[] args) {
11 ExportFile apk = new ExportFile();
12 String infilePath = EXPORT_PATH + "test.zip";
13 String outfilePath = EXPORT_PATH + "hex.txt";
14 apk.fileToHex(infilePath, outfilePath);
15 //hex val
16 String val = "";
17 apk.hexToFile(val, "a.zip");
18 }
19
20 /**
21 * 文件转成十六进制
22 *
23 * @param infilePath 转为16进制的文件
24 * @param outfilePath 16进制 txt
25 */
26 public void fileToHex(String infilePath, String outfilePath) {
27 try {
28 StringBuffer sb = new StringBuffer();
29 FileInputStream fis = new FileInputStream(infilePath);
30 java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
31
32 byte[] buffer = new byte[1024];
33 int read = 1024;
34 int readSize = 1024;
35 while (read == readSize) {
36 read = fis.read(buffer, 0, readSize);
37 bos.write(buffer, 0, read);
38 }
39 byte[] result = bos.toByteArray();
40 // 字节数组转成十六进制
41 String str = byte2HexStr(result);
42 System.out.println("HexStr:" + str);
43 /*
44 * 将十六进制串保存到txt文件中
45 */
46 PrintWriter pw = new PrintWriter(new FileWriter(outfilePath));
47 pw.println(str);
48 pw.close();
49 } catch (IOException e) {
50 e.printStackTrace();
51 }
52 }
53
54 /**
55 * 十六进制转成文件
56 *
57 * @param hex
58 * @param filePath
59 */
60 public static void hexToFile(String hex, String filePath) {
61 StringBuilder sb = new StringBuilder();
62 sb.append(hex);
63 saveToFile(sb.toString().toUpperCase(), EXPORT_PATH + filePath);
64 }
65
66 /**
67 * hex 转为文件
68 *
69 * @param src
70 * @param output
71 */
72 public static void saveToFile(String src, String output) {
73 if (src == null || src.length() == 0) {
74 return;
75 }
76 try {
77 FileOutputStream out = new FileOutputStream(new File(output));
78 byte[] bytes = src.getBytes();
79 for (int i = 0; i < bytes.length; i += 2) {
80 out.write(charToInt(bytes[i]) * 16 + charToInt(bytes[i + 1]));
81 }
82 out.close();
83 } catch (Exception e) {
84 e.printStackTrace();
85 }
86 }
87
88 private static int charToInt(byte ch) {
89 int val = 0;
90 if (ch >= 0x30 && ch <= 0x39) {
91 val = ch - 0x30;
92 } else if (ch >= 0x41 && ch <= 0x46) {
93 val = ch - 0x41 + 10;
94 }
95 return val;
96 }
97
98 /*
99 * 实现字节数组向十六进制的转换方法一
100 */
101 public static String byte2HexStr(byte[] b) {
102 String hs = "";
103 String stmp = "";
104 for (int n = 0; n < b.length; n++) {
105 stmp = (Integer.toHexString(b[n] & 0XFF));
106 if (stmp.length() == 1) {
107 hs = hs + "0" + stmp;
108 } else {
109 hs = hs + stmp;
110 }
111 }
112 return hs.toUpperCase();
113 }
114 }
来源:oschina
链接:https://my.oschina.net/u/4312979/blog/3405611