I'm who I am .

文件转化为字节数组

上一篇 / 下一篇  2015-01-15 12:57:18 / 个人分类:java

//---------------------getBytesFromFile------------------------------------------------------
 /**
     * 文件转化为字节数组
     * 字节数组的大小,收到jvm最大内存的限制
     *  System.out.println("jvm最大内存是:"+Runtime.getRuntime().maxMemory()/1024/1024+"M");
     * @param file
     * @return
     */  
    public static byte[] getBytesFromFile(File file) {  
        byte[] ret = null;  
       // System.out.println("执行getBytesFromFile方法中");
        
        if (file == null) { 
                // log.error("helper:the file is null!"); 
            System.out.println("文件找不到。。");
                return null; 
            }
       
        long fileSize = file.length();
       
        if (fileSize > Integer.MAX_VALUE) {
            System.out.println("file too big...");
            return null;
        }

        try { 
            if (!file.exists()) {
                throw new FileNotFoundException("文件不存在,请检查文件路径是否正确");
            }
            FileInputStream in = new FileInputStream(file); 
            ByteArrayOutputStream ut = new ByteArrayOutputStream();
            byte[] b = new byte[BUFFER]; 
            int n; 
            while ((n = in.read(b)) != -1) { 
                out.write(b, 0, n); 
            } 
            in.close(); 
            out.close(); 
            ret = out.toByteArray(); 
        } catch (IOException e) { 
            // log.error("helper:get bytes from file process error!"); 
            e.printStackTrace(); 
        } 
        //System.out.println("文件压缩前字节长度:"+(float)ret.length/1024/1024+"M");
        return ret; 
    }
 

TAG:

 

评分:0

我来说两句

日历

« 2024-03-31  
     12
3456789
10111213141516
17181920212223
24252627282930
31      

数据统计

  • 访问量: 53971
  • 日志数: 51
  • 建立时间: 2015-01-04
  • 更新时间: 2015-05-27

RSS订阅

Open Toolbar