package zs;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode; public class FileUtils {
public byte[] getContent(String filePath) throws IOException {
File file = new File(filePath);
long fileSize = file.length();
if (fileSize > Integer.MAX_VALUE) {
System.out.println("file too big...");
return null;
}
FileInputStream fi = new FileInputStream(file);
byte[] buffer = new byte[(int) fileSize];
int offset = 0;
int numRead = 0;
while (offset < buffer.length
&& (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += numRead;
}
// 确保所有数据均被读取
if (offset != buffer.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}
fi.close();
return buffer;
} /**
* the traditional io way
*
* @param filename
* @return
* @throws IOException
*/
public static byte[] toByteArray(String filename) throws IOException { File f = new File(filename);
if (!f.exists()) {
throw new FileNotFoundException(filename);
} ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while (-1 != (len = in.read(buffer, 0, buf_size))) {
bos.write(buffer, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
bos.close();
}
} /**
* NIO way
*
* @param filename
* @return
* @throws IOException
*/
public static byte[] toByteArray2(String filename) throws IOException { File f = new File(filename);
if (!f.exists()) {
throw new FileNotFoundException(filename);
} FileChannel channel = null;
FileInputStream fs = null;
try {
fs = new FileInputStream(f);
channel = fs.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
while ((channel.read(byteBuffer)) > 0) {
// do nothing
// System.out.println("reading");
}
return byteBuffer.array();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能
*
* @param filename
* @return
* @throws IOException
*/
public static byte[] toByteArray3(String filename) throws IOException { FileChannel fc = null;
try {
fc = new RandomAccessFile(filename, "r").getChannel();
MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,
fc.size()).load();
System.out.println(byteBuffer.isLoaded());
byte[] result = new byte[(int) fc.size()];
if (byteBuffer.remaining() > 0) {
// System.out.println("remain");
byteBuffer.get(result, 0, byteBuffer.remaining());
}
return result;
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
fc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

读取Java文件到byte数组的三种方式的更多相关文章

  1. Java反射获取class对象的三种方式,反射创建对象的两种方式

    Java反射获取class对象的三种方式,反射创建对象的两种方式 1.获取Class对象 在 Java API 中,提供了获取 Class 类对象的三种方法: 第一种,使用 Class.forName ...

  2. Java 文件和byte数组转换

    /** * 获得指定文件的byte数组 */ private byte[] getBytes(String filePath){ byte[] buffer = null; try { File fi ...

  3. 数组的三种方式总结 多维数组的遍历 Arrays类的常用方法总结

    一.数组的三种声明方式总结 public class WhatEver { public static void main(String[] args) { //第一种 例: String[] tes ...

  4. Java中 实现多线程成的三种方式(继承,实现,匿名内部类)

    ---------------------------------------------------------------------------------------------------- ...

  5. 【java多线程】多线程的创建三种方式--笔记

    申明:线程的概念以及进程的相关概念,可以参考网络上其他资料,这里只讨论多线程是怎么实现. 一.多线程的简单理解 明白什么是多线程,小生通俗一点的理解为:在一个程序里,我想同时让这个程序完成多个任务. ...

  6. Java反射获取类对象的三种方式

    package demo01; /* * 获取一个类的class文件对象的三种方式 * 1.对象获取 * 2.类名获取 * 3.Class类的静态方法获取 */ public class Reflec ...

  7. java base64编码、解码的三种方式

      java base64编码.解码 CreationTime--2018年7月24日10点38分 Author:Marydon 1.方式一:DatatypeConverter 说明:使用jdk自带的 ...

  8. PHP数组缓存:三种方式JSON、序列化和var_export的比较

    使用PHP的站点系统,在面对大数据量的时候不得不引入缓存机制.有一种简单有效的办法是将PHP的对象缓存到文件里.下面我来对这3种缓存方法进行说明和比较. 第一种方法:JSONJSON缓存变量的方式主要 ...

  9. JavaScript中清空数组的三种方式

    方式1,splice ? 1 2 3 var ary = [1,2,3,4]; ary.splice(0,ary.length); console.log(ary); // 输出 [],空数组,即被清 ...

随机推荐

  1. 2016/05/10 thinkphp 3.2.2 ①系统常量信息 ②跨控制器调用 ③连接数据库配置及Model数据模型层 ④数据查询

    [系统常量信息] 获取系统常量信息: 如果加参数true,会分组显示: 显示如下: [跨控制器调用] 一个控制器在执行的时候,可以实例化另外一个控制,并通过对象访问其指定方法. 跨控制器调用可以节省我 ...

  2. 2016/3/18 ①PHP基础 ② PHP函数 ③其他函数(随机数、关于日期) ④正则表达式 ⑤字符串处理

    一.PHP基础 1,标记和注释 ①<?php?> ②单行注释// 多行注释/**    */2, 输出语句 ①echo输出 echo可以输出多个字符串,用逗号隔开. ②print输出 pr ...

  3. 2016/3/17 Mysq select 数学函数 字符串函数 时间函数 系统信息函数 加密函数

    一,数学函数主要用于处理数字,包括整型.浮点数等. ABS(X) 返回x的绝对值 SELECT ABS(-1)--返回1 CEll(X),CEILING(x)  返回大于或等于x的最小整数 SELEC ...

  4. css的白富美

    1,CSS(Cascading Style Sheet)是用来装饰HTML的,当浏览器读到这样一个样式的时候,它就会按照这个文档进行格式化(渲染) 2,CSS的组成:选择器和声明,声明又包括属性和属性 ...

  5. HDU3829 Cat VS Dog —— 最大独立集

    题目链接:https://vjudge.net/problem/HDU-3829 Cat VS Dog Time Limit: 2000/1000 MS (Java/Others)    Memory ...

  6. [USACO 2004DEC] Navigation Nightmare

    [题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=3362 [算法] 带权并查集 时间复杂度 : O(NlogN) [代码] #inclu ...

  7. pymemcache get start

    Getting started! A comprehensive, fast, pure-Python memcached client library. Basic Usage from pymem ...

  8. Python+页面元素高亮源码实例

    简单写了一个页面元素高亮的方法,原理就是在python中调用js实现元素高亮,分享一下源码如下: 1.元素高亮源码 Js调用 js = "var q=document.getElementB ...

  9. 在Centos下安装httpd、php、Mysql并配置(转载)

    转自:http://club.jledu.gov.cn/?action-viewspace-itemid-299020 1.安装Apahce, PHP, Mysql, 以及php连接mysql库组件. ...

  10. IPC进程之间通信的几种方式

    概念 进程间通信就是在不同进程之间传播或交换信息,那么不同进程之间存在着什么双方都可以访问的介质呢?进程的用户空间是互相独立的,一般而言是不能互相访问的,唯一的例外是 共享内存区 .但是,系统空间却是 ...