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 }
  • 相关阅读:
    沙龙:超越敏捷 召集中![广州]
    超级扫盲什么是设计模式?
    大话UML
    敏捷开发纵横谈
    超越竞争对手的秘密武器技术重用
    1.1 基础知识——CMMI是什么东西?
    Tutorial 2: Rendering a Triangle
    Tutorial 4: 3D Spaces
    Tutorial 5: 3D Transformation
    D3D11中的绘制
  • 原文地址:https://www.cnblogs.com/pcheng/p/6913535.html
Copyright © 2011-2022 走看看