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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM