全面了解java byte数组与文件读写
全面了解javabyte数组与文件读写
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
publicclassFileHelper{
<spanstyle="white-space:pre"></span>//第一种获取文件内容方式
publicbyte[]getContent(StringfilePath)throwsIOException{
Filefile=newFile(filePath);
longfileSize=file.length();
if(fileSize>Integer.MAX_VALUE){
System.out.println("filetoobig...");
returnnull;
}
FileInputStreamfi=newFileInputStream(file);
byte[]buffer=newbyte[(int)fileSize];
intoffset=0;
intnumRead=0;
while(offset<buffer.length
&&(numRead=fi.read(buffer,offset,buffer.length-offset))>=0){
offset+=numRead;
}
//确保所有数据均被读取
if(offset!=buffer.length){
thrownewIOException("Couldnotcompletelyreadfile"
+file.getName());
}
fi.close();
returnbuffer;
}
//第二种获取文件内容方式
publicbyte[]getContent2(StringfilePath)throwsIOException
{
FileInputStreamin=newFileInputStream(filePath);
ByteArrayOutputStreamout=newByteArrayOutputStream(1024);
System.out.println("bytesavailable:"+in.available());
byte[]temp=newbyte[1024];
intsize=0;
while((size=in.read(temp))!=-1)
{
out.write(temp,0,size);
}
in.close();
byte[]bytes=out.toByteArray();
System.out.println("bytessizegotis:"+bytes.length);
returnbytes;
}
//将byte数组写入文件
publicvoidcreateFile(Stringpath,byte[]content)throwsIOException{
FileOutputStreamfos=newFileOutputStream(path);
fos.write(content);
fos.close();
}
}
以上这篇全面了解javabyte数组与文件读写就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。