zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    2015.10.9js(页面坐标)
    2015.8.2js-19(完美运动框架)
    2015.7.12js-11(DOM基础)
    2015.7.7js-07-2(基础)
    2015.7.11js-10(无缝滚动)
    2015.7.10js-07(简单时间)
    2015.7.8js-05(简单日历)
    2015-7.7森林探秘季
    jquery scroll()滚动条事件
    资源(127.0.0.1)处于联机状态,但未对连接尝试做出反应
  • 原文地址:https://www.cnblogs.com/pcheng/p/6913535.html
Copyright © 2011-2022 走看看