JAVA中文件与Byte数组相互转换的方法
JAVA中文件与Byte数组相互转换的方法,如下:
1 public class FileUtil {2
3 //将文件转换成Byte数组
4 public static byte[] getBytesByFile(String pathStr) {
5 File file = new File(pathStr);
6 try {
7 FileInputStream fis = new FileInputStream(file);
8 ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
9 byte[] b = new byte[1000];
10 int n;
11 while ((n = fis.read(b)) != -1) {
12 bos.write(b, 0, n);
13 }
14 fis.close();
15 byte[] data = bos.toByteArray();
16 bos.close();
17 return data;
18 } catch (Exception e) {
19 e.printStackTrace();
20 }
21 return null;
22 }
23
24 //将Byte数组转换成文件
25 public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
26 BufferedOutputStream bos = null;
27 FileOutputStream fos = null;
28 File file = null;
29 try {
30 File dir = new File(filePath);
31 if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
32 dir.mkdirs();
33 }
34 file = new File(filePath + "\\" + fileName);
35 fos = new FileOutputStream(file);
36 bos = new BufferedOutputStream(fos);
37 bos.write(bytes);
38 } catch (Exception e) {
39 e.printStackTrace();
40 } finally {
41 if (bos != null) {
42 try {
43 bos.close();
44 } catch (IOException e) {
45 e.printStackTrace();
46 }
47 }
48 if (fos != null) {
49 try {
50 fos.close();
51 } catch (IOException e) {
52 e.printStackTrace();
53 }
54 }
55 }
56 }
57 }
以上是 JAVA中文件与Byte数组相互转换的方法 的全部内容, 来源链接: utcz.com/z/391005.html