读取 Java 文件到 Byte 数组的三种方法 (总结)
Пакет ZS; импорт java.io.bufferedinputstream; импорт java.io.bytearrayoutputstream; импорт java.io.file; импорт java.io.fileinputstream; импорт java.io.filenotfoundexception; импорт java.io.ioexcept 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 = filePath); Integer.max_value) {system.out.println ("файл слишком большой ..."); return null;} fileInputStream fi = new FileInputStream (file); Byte [] buffer = new Byte [(int) fileSize]; int offset = 0; int numbred = 0; Offset))> = 0) {Offset + = numRead;} // 确保所有数据均被读取 if (offset! = buffer.length) {throw new ioException ("Не удалось полностью прочитать файл" + file.getName ());} fi.close (); return buffer;}/** * * * * * * * * * * * * * * * * * * * * * * * * * * 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! (IoException e) {e.printstacktrace (); throw e;} наконец {try {in.close ();} catch (ioexception e) {e.printstacktrace ();} bos.close ();}}/** * nio way * @parame * @return * @throws ioexcept 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) {// ничего не делать // system.out.println ("чтение");} вернуть bytebuffer.array ();} catch (ioexcept e) {e.printstacktrace (); (Ioexception e) {e.printstacktrace ();} try {fs.close ();} catch (ioexception e) {e.printstacktrace ();}}}/** * maped filebebuffer 可以在处理大文件时 提升性能 提升性能 * @parame * @return * @throws ioexcept Имя файла) бросает ioException {fileChannel fc = null; try {fc = new randomaccessfile (имя файла, "r"). getChannel (); mapedbytebuffer bytebuffer = fc.map (mapmode.read_only, 0, fc.size (). = new Byte [(int) fc.size ()]; if (bytebuffer.reming ()> 0) {// system.out.println ("остаться"); bytebuffer.get (result, 0, bytebuffer.reming ());} return result;} catch (ioexception e) {e.printStacktrace () trake e witch}} trake Exception e) {e.printStackTrace (); {fc.close ();} catch (ioexception e) {e.printstacktrace ();}}}}以上这篇读取 java 文件到 byte 数组的三种方法 (总结) 就是小编分享给大家的全部内容了 , 希望能给大家一个参考 , 也希望大家多多支持武林网。