讀取java文件到字節數組的三種方法(總結)
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(fileize> integer.max_value){system.out.ut.println(“文件太大...”); returninputStream fi = new FileInputStream(file); fi.Read(緩衝,偏移,buffer.length -offset))> = 0){offset + = numRead;} // if(offset!= buffer.length){拋出新的ioexception(“無法完全讀取文件” + file.getName(); getName();} fi.close;} fi.close();} firer firer firer firer firer; @thring ioException */public static byte [] tobyTearray(string fileAname)拋出ioexception {file f = new file(fileName); if(!f.exists()){thort new FileNotFoundException(thort fore filenotfoundexception(fileNotFoundException(fileName);} null; try {in =新的bufferedInputStream(new fileInputStream(f)); int buf_size = 1024; byte [] buffer = new byte = new Byte [buf_size]; int len = 0; while(-1! =(len =(len = in.Read in.Read in.Read(buffer,buf_size)) bos.tobytearray();} catch(ioexception e){e.printstacktrace(); throw e;}最後{try {in.close();} catch(ioexception e){e.printstacktrace(e.printstacktrace(e.printstacktrace() */公共靜態字節[] fs.GetChannel(); bytebuffer bytebuffer = bytebuffer.allocate(((int)channel.size()); while((((channel.read(bytebuffer)))> 0){// nothing nothing/ noth noths.ut.out.out.out.ut.println(reading') 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 */公共靜態字節[] 0,fc.size())。load(); system.out.println(bytebuffer.isloaded()); byte []結果= new byte [(int)fc.size(); if(bytebuffer.remaining.remaining(bytebuffer.remaining()> 0)> 0) bytebuffer.remaining());}返回結果;} catch(ioexception e){e.printstacktrace(); throw e;}最後{try {fc.close();} catch(ioexception e)以上這篇讀取java文件到字節數組的三種方法(總結),希望能給大家一個參考,也希望大家多多支持武林網。 ,也希望大家多多支持武林網。