读取Java文件到byte数组的三种方式
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数组的三种方式的更多相关文章
- Java反射获取class对象的三种方式,反射创建对象的两种方式
Java反射获取class对象的三种方式,反射创建对象的两种方式 1.获取Class对象 在 Java API 中,提供了获取 Class 类对象的三种方法: 第一种,使用 Class.forName ...
- Java 文件和byte数组转换
/** * 获得指定文件的byte数组 */ private byte[] getBytes(String filePath){ byte[] buffer = null; try { File fi ...
- 数组的三种方式总结 多维数组的遍历 Arrays类的常用方法总结
一.数组的三种声明方式总结 public class WhatEver { public static void main(String[] args) { //第一种 例: String[] tes ...
- Java中 实现多线程成的三种方式(继承,实现,匿名内部类)
---------------------------------------------------------------------------------------------------- ...
- 【java多线程】多线程的创建三种方式--笔记
申明:线程的概念以及进程的相关概念,可以参考网络上其他资料,这里只讨论多线程是怎么实现. 一.多线程的简单理解 明白什么是多线程,小生通俗一点的理解为:在一个程序里,我想同时让这个程序完成多个任务. ...
- Java反射获取类对象的三种方式
package demo01; /* * 获取一个类的class文件对象的三种方式 * 1.对象获取 * 2.类名获取 * 3.Class类的静态方法获取 */ public class Reflec ...
- java base64编码、解码的三种方式
java base64编码.解码 CreationTime--2018年7月24日10点38分 Author:Marydon 1.方式一:DatatypeConverter 说明:使用jdk自带的 ...
- PHP数组缓存:三种方式JSON、序列化和var_export的比较
使用PHP的站点系统,在面对大数据量的时候不得不引入缓存机制.有一种简单有效的办法是将PHP的对象缓存到文件里.下面我来对这3种缓存方法进行说明和比较. 第一种方法:JSONJSON缓存变量的方式主要 ...
- JavaScript中清空数组的三种方式
方式1,splice ? 1 2 3 var ary = [1,2,3,4]; ary.splice(0,ary.length); console.log(ary); // 输出 [],空数组,即被清 ...
随机推荐
- [办公自动化]EXCEL不大,但是保存很慢
今天同事有一个excel文件.office 2007格式的. 折腾了半天.按照以往的经验,定位-对象,应该可以删除. 后来在“编辑”窗格的“查找和选择”里面,单击“选择窗格“.可以看到很多”pictu ...
- RabbitMQ常用命令、管理界面
1.运行CMD,cd切换到RabbitMQ安装目录sbin下E:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.2\sbin 执行 rabbitm ...
- Where Are You Standing?
/*********************************************************************** * Where Are You Standing? * ...
- bzoj4881 线段游戏——上升序列方案数
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4881 连题意都转化不了了... 题意是要求从一个数列中选出两个上升序列的方案数: 先判断是否 ...
- redis发布(pub)、订阅(sub)模式
前言:redis提供了很多种功能或模式,可以运用在不同的场景下,今天记录下redis中的发布.订阅模式的基本使用 注redis安装及主从搭建请参考我其他博文http://www.cnblogs.com ...
- 在selenium中一些相对常用的JavaScript事件
输入框输入: 1.找到输入框的id,然后进行输入操作 ordinal :输入框的id parameter :需要输入的内容 browser.execute_script("document. ...
- bzoj 3329: Xorequ【数位dp+矩阵乘法】
注意第一问不取模!!! 因为a+b=a|b+a&b,a^b=a|b-a&b,所以a+b=a^b+2(a&b) x^3x==2x可根据异或的性质以转成x^2x==3x,根据上面的 ...
- bzoj 3143 [Hnoi2013]游走【高斯消元+dp】
参考:http://blog.csdn.net/vmurder/article/details/44542575 和2337有点像 设点u的经过期望(还是概率啊我也分不清,以下都分不清)为\( x[u ...
- UVA - 10859 Placing Lampposts 放置街灯
Placing Lampposts 传送门:https://vjudge.net/problem/UVA-10859 题目大意:给你一片森林,要求你在一些节点上放上灯,一个点放灯能照亮与之相连的所有的 ...
- Linux的防火墙概念
#linux的防火墙概念#因为如果你不关防火墙,很可能运行 django.nginx.mysql出错#防火墙可能会阻挡端口流量的 出口#也会阻挡外来请求的 入口 #selinux iptables f ...