读取Java文件到byte数组的三种方法(总结)

 更新时间:2016年08月22日 10:28:56   投稿:jingxian  
下面小编就为大家带来一篇读取Java文件到byte数组的三种方法(总结)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

读取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二叉树查询原理深入分析讲解

    Java二叉树查询原理深入分析讲解

    这篇文章主要介绍了Java二叉树查询原理,二叉查找树,又称二叉排序树,亦称二叉搜索树,是数据结构中的一类。在一般情况下,查找效率比链表结构要高
    2022-11-11
  • mybatis中resultMap 标签的使用教程

    mybatis中resultMap 标签的使用教程

    resultMap 标签用来描述如何从数据库结果集中来加载对象,这篇文章重点给大家介绍mybatis中resultMap 标签的使用,感兴趣的朋友一起看看吧
    2018-07-07
  • Java线程安全状态专题解析

    Java线程安全状态专题解析

    线程安全是多线程编程时的计算机程序代码中的一个概念。在拥有共享数据的多条线程并行执行的程序中,线程安全的代码会通过同步机制保证各个线程都可以正常且正确的执行,不会出现数据污染等意外情况
    2022-03-03
  • JavaWeb中过滤器Filter的用法详解

    JavaWeb中过滤器Filter的用法详解

    过滤器通常对一些web资源进行拦截,做完一些处理器再交给下一个过滤器处理,直到所有的过滤器处理器,再调用servlet实例的service方法进行处理。本文将通过示例为大家讲解JavaWeb中过滤器Filter的用法与实现,需要的可以参考一下
    2022-08-08
  • Spring实战之让Bean获取Spring容器操作示例

    Spring实战之让Bean获取Spring容器操作示例

    这篇文章主要介绍了Spring实战之让Bean获取Spring容器操作,结合实例形式分析了Bean获取Spring容器的相关原理、实现方法及操作注意事项,需要的朋友可以参考下
    2019-11-11
  • 解决IDEA误删out目录下的文件导致404无法访问的问题

    解决IDEA误删out目录下的文件导致404无法访问的问题

    这篇文章主要介绍了解决IDEA误删out目录下的文件导致404无法访问的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • Java中的隐式参数和显示参数实例详解

    Java中的隐式参数和显示参数实例详解

    这篇文章主要介绍了Java中的隐式参数和显示参数是什么,另外还有两个小例子帮助大家理解,需要的朋友可以参考下。
    2017-08-08
  • Java获取resources下文件路径的几种方法及遇到的问题

    Java获取resources下文件路径的几种方法及遇到的问题

    这篇文章主要给大家介绍了关于Java获取resources下文件路径的几种方法及遇到的问题,在Java开发中经常需要读取项目中resources目录下的文件或获取资源路径,需要的朋友可以参考下
    2023-12-12
  • IntelliJ IDEA启动错误:插件冲突处理的解决方案

    IntelliJ IDEA启动错误:插件冲突处理的解决方案

    在使用 IntelliJ IDEA 进行开发时,我们可能会遇到各种启动错误,本文将详细介绍一种常见的错误:插件冲突,并提供解决方案,文中通过图文和代码介绍的非常详细,具有一定的参考价值,需要的朋友可以参考下
    2025-02-02
  • java.lang.NullPointerException异常的几种原因及解决方案

    java.lang.NullPointerException异常的几种原因及解决方案

    本文主要介绍了java.lang.NullPointerException异常的几种原因及解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04

最新评论