java 把文件转化为字节数组

 2023-09-05 阅读 54 评论 0

摘要:Java中如何把文件(file)转化字节数组呢? 方式一: Java代码 /***文件转换为二进制数组**@paramfile文件对象*@return*@throwsIOException*/publicstaticbyte[]fileTobytes(finalFilefile)throwsIOException{byte[]data=null;if(f

Java 中如何把文件(file)转化字节数组呢?

方式一:

Java代码  收藏代码
  1. /** 
  2.     * 文件转换为二进制数组 
  3.     * 
  4.     * @param file 文件对象 
  5.     * @return 
  6.     * @throws IOException 
  7.     */  
  8.    public static byte[] fileTobytes(final File file) throws IOException {  
  9.        byte[] data = null;  
  10.        if (file.exists()) {  
  11.            FileInputStream fileInputStream = new FileInputStream(file);  
  12.            int length = fileInputStream.available();  
  13.            data = new byte[length];  
  14.            fileInputStream.read(data);  
  15.            fileInputStream.close();  
  16.        }  
  17.        return data;  
  18.    }  

 方式二:

Java代码  收藏代码
  1. /*** 
  2.      * read file ,convert file to byte array 
  3.      *  
  4.      * @param file 
  5.      * @return 
  6.      * @throws IOException 
  7.      */  
  8.     public static byte[] readBytes4file(File file) throws IOException{  
  9.         BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));          
  10.         ByteArrayOutputStream out = new ByteArrayOutputStream(1024);          
  11.          
  12. //        System.out.println("Available bytes:" + in.available());          
  13.          
  14.         byte[] temp = new byte[1024];          
  15.         int size = 0;          
  16.         while ((size = in.read(temp)) != -1) {          
  17.             out.write(temp, 0, size);          
  18.         }          
  19.         in.close();          
  20.          
  21.         byte[] content = out.toByteArray();  
  22.         return content;  
  23.     }  

 

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/1141.html

上一篇:jedis的简介

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息