全面了解java byte數(shù)組與文件讀寫
更新時(shí)間:2016年08月22日 10:41:26 投稿:jingxian
下面小編就為大家?guī)硪黄媪私鈐ava byte數(shù)組與文件讀寫。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
全面了解java byte數(shù)組與文件讀寫
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileHelper {
<span style="white-space:pre"> </span>//第一種獲取文件內(nèi)容方式
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;
}
// 確保所有數(shù)據(jù)均被讀取
if (offset != buffer.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}
fi.close();
return buffer;
}
//第二種獲取文件內(nèi)容方式
public byte[] getContent2(String filePath) throws IOException
{
FileInputStream in=new FileInputStream(filePath);
ByteArrayOutputStream out=new ByteArrayOutputStream(1024);
System.out.println("bytes available:"+in.available());
byte[] temp=new byte[1024];
int size=0;
while((size=in.read(temp))!=-1)
{
out.write(temp,0,size);
}
in.close();
byte[] bytes=out.toByteArray();
System.out.println("bytes size got is:"+bytes.length);
return bytes;
}
//將byte數(shù)組寫入文件
public void createFile(String path, byte[] content) throws IOException {
FileOutputStream fos = new FileOutputStream(path);
fos.write(content);
fos.close();
}
}
以上這篇全面了解java byte數(shù)組與文件讀寫就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
springboot2 生產(chǎn)部署注意事項(xiàng)及示例代碼
這篇文章主要介紹了springboot2 生產(chǎn)部署注意事項(xiàng)及示例代碼,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04
SpringMVC?RESTFul及REST架構(gòu)風(fēng)格介紹
這篇文章主要為大家介紹了SpringMVC?RESTFul及REST架構(gòu)風(fēng)格介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
SpringBoot實(shí)現(xiàn)上傳文件到AWS S3的代碼
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)上傳文件到AWS S3的代碼,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下2020-10-10

