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. 8核 16g 及时释放内存空间

    del  释放 大变量 所在内存空间 GB数据

  2. What are some advantages of using Node.js over a Flask API?

    https://www.quora.com/What-are-some-advantages-of-using-Node-js-over-a-Flask-API Flask is a Python w ...

  3. SetLocalTime API函数设置本地时间(DateTimeToSystemTime函数,把TDateTime转换成TSystemTime)

    procedure setLocalDateTime(Value: TDateTime);var  lSystemDateTime: TSystemTime;begin  DateTimeToSyst ...

  4. RFC 在OA中创建PR

    创建PR:BAPI_REQUISITION_CREATE BAPI_PR_CREATE                 "Create Enjoy Purchase Requisistion ...

  5. POJ - 3041 Asteroids(最小点覆盖数)

    1.有一个n*n的矩阵,在矩阵上有k个行星,用武器射击一次可以消灭一行或者一列的行星,求消灭所有的行星的最少射击次数. 2.最小点覆盖数 = 最大匹配数 主要在于转化:看图: 这样,在建成的二分图中, ...

  6. IOS应用在iPhone5和iPhone5s上不能全屏显示,应用画面上下各有1条黑色的解决方案

    设置启动图片就可以了: 添加启动图: 接着设置为启动图: 这样就ok了

  7. 洛谷 P2444 [ POI 2000 ] 病毒 —— AC自动机+dfs

    题目:https://www.luogu.org/problemnew/show/P2444 AC自动机上 dfs,不走结尾点,如果走出环就是有无限长度的串: RE无数,原来是数组开成 2000 的了 ...

  8. php 和 js之间使用json通信

    有时候我们需要用后台从数据库中得到的数据在js中进行处理,但是当从php中获取到数据的时候,使用的是键值对形式的多维关联数组.而我们知道,js只支持索引数组,不支持关联数组,这个时候从后台传递过来的数 ...

  9. java笔记之IO1

    File:文件和目录(文件夹)路径名的抽象表示形式 * 构造方法: *   File(String pathname):根据一个路径得到File对象 *   File(String parent, S ...

  10. sql server 变量 字符串拼接

    参考:SQL server中null+字符串,isnull以及把查询结果赋给一个字符变量组成另一个查询语句  1.开始定义的字符串都为null.例如:declare @sql,那么@sql就是null ...