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. URL传参中文乱码的一种解决方法

    中文乱码是由于,发送和接收方使用的编码解码格式不一致导致,以下是关于url传参解决中文乱码的一种方法,最后根据各种编码格式尝试解码,发现正确的解码格式 string strQueryString = ...

  2. unix2dos/dos2unix

    dos2unix命令用来将DOS格式的文本文件转换成UNIX格式的(DOS/MAC to UNIX text file format converter).DOS下的文本文件是以\r\n作为断行标志的 ...

  3. noteexpress使用指南

    软件功能:在写论文时直接调用参考数据并输出正规的格式. (以下简称NE) A.下载安装 下载地址:Note-express - Bibliography Software  选择相应的学校进行下载,相 ...

  4. Oracle - 查询语句 - 多表关联查询

    /* SQL语句的历史版本 SQL89 比较多 SQL92 SQL99 多表关联查询 笛卡尔积 等值关联查询 非等值关联查询 左外连接 右外连接 全外连接 自连接 */ --------------- ...

  5. 3.5Linux设备驱动--块设备(一)之概念和框架☆☆

    基本概念   块设备(blockdevice) --- 是一种具有一定结构的随机存取设备,对这种设备的读写是按块进行的,他使用缓冲区来存放暂时的数据,待条件成熟后,从缓存一次性写入设备或者从设备一次性 ...

  6. android编译openssl静态库.a

    github上有一个开源项目,已经为你编译openssl建好了工程. 地址:https://github.com/aluvalasuman/OpenSSL1.0.1cForAndroid 选择需要的版 ...

  7. UICollectionView与UITableView混用手势冲突

    前言 最近在重构某个模块,以后别人封装的所谓的基类就像一坨死一样,看见就恶心,相信同行的你们能够明白那种心情.为什么要重构?并不是真的因为它像一坨死,而是因为这个模块是用户使用最频繁的,而且出现了不少 ...

  8. AutoIT: 开发界面结合GUI automation和Watir Automation

    可以应用AutoIT开发出界面,从而把AutoIT对GUI的自动化测试与Watir对web的自动化测结合在一起.以下代码是我学习GUI界面开发的实例代码.1. 当点击Watir_Test_Button ...

  9. pymemcache get start

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

  10. 杂项:WebRTC

    ylbtech-杂项:WebRTC WebRTC,名称源自网页实时通信(Web Real-Time Communication)的缩写,是一个支持网页浏览器进行实时语音对话或视频对话的技术,是谷歌20 ...