读取 Java 文件到 byte 数组的三种方法 (总结)
pacote zs; importar java.io.bufferedInputStream; importar java.io.byteArrayoutputStream; importar java.io.file; importar java.io.fileInputStream; import java.io.fileNotFoundException; import java.io.ioxception; 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 ("arquivo muito grande ..."); retorna null;} fileInputStream fi = new FileInputStream (file); byte [] buffer = new Byte [(int) fileSize]; int offset = 0; INT = 0; While (OffSet <luffer.lng.lng.Length &. offset))> = 0) {offset + = numread;} // 确保所有数据均被读取 if (offset! = buffer.length) {tiro a nova ioexception ("não conseguiu ler completamente o arquivo" + file.getName ());} fi.close.close (); TobyteArray (nome do arquivo de string) lança IoException {arquivo f = novo arquivo (nome do arquivo); if (! f.exists ()) {tiro o novo fileNotFoundException (nome do arquivo);} byteArrayoutTream bos = newTearTearTUtTream ((int) f.LEstRay (); FileInputStream (f)); int buf_size = 1024; byte [] buffer = novo byte [buf_size]; int len = 0; while (-1! {E.PrintStackTrace (); Throw e;} finalmente {try {in.close ();} catch (ioexception e) {e.printStacktrace ();} bos.close ();}}}/** * nio way * * @param filename * @renTururn * @THOException * Ioexception {arquivo f = novo arquivo (nome do arquivo); if (! F.exists ()) {lança novo fileNotFoundException (nome do arquivo);} filechannel canal = null; fileInputStream fs = null; try {fs = new FileInTream (f); canal = fs.getChanNel (por byteB (fs = new FileInpTream (f); canal = fs.getCanNel () por {fs = FileInTream (f); Channel.size ()); while ((canal.read (bytebuffer))> 0) {// não faça nada // System.out.println ("Reading");} Return bytebuffer.array ();} Catch (ioexception e) {e.printstack) {E.PrintStackTrace ();} tente {fs.close ();} catch (ioexception e) {e.printStackTrace ();}}}/** * arquivo mapeado way mapedbytebuffer 可以在处理大文件时 , 提升性能 * * @param filename * @@extionsexcember 可以在处理大文件时 , 提升性能 * * @param FILNAME * Ioexception {filechannel fc = null; try {fc = new RandomAccessFile (nome do arquivo, "r"). GetChannel (); mapedbytebuffer byteBuffer = fc.map (mapMode.read_only, 0, fc.size (). Carreg (); Sistema.out.out.print.printnnnin, 0, fc.size (). Carregamento (); Sistema.out.out.Int.PRATLN; byte [(int) fc.size ()]; if (bytebuffer.remaining ()> 0) {// System.out.println ("permanecem"); bytebuffer.get (resultado, 0, bytebuffer.Remaining ());} REIRT; {fc.close ();} catch (ioexception e) {e.printStackTrace ();}}}}以上这篇读取 Java 文件到 byte 数组的三种方法 (总结) 就是小编分享给大家的全部内容了 , 希望能给大家一个参考 , 也希望大家多多支持武林网。