--sunfruit
java讀取文件或是文件流的代碼,涵蓋了讀取jar文件中的文件流,網(wǎng)絡(luò)文件流等,有些讀取方式為了防止編碼轉(zhuǎn)換帶來的問題,采取了動態(tài)byte[]的方式讀取,源碼如下
import java.io.BufferedInputStream;
import java.io.File;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Util {
public Util() {
}
/**
* 讀取源文件內(nèi)容
* @param filename String 文件路徑
* @throws IOException
* @return byte[] 文件內(nèi)容
*/
public static byte[] readFile(String filename) throws IOException {
File file =new File(filename);
if(filename==null || filename.equals(""))
{
throw new NullPointerException("無效的文件路徑");
}
long len = file.length();
byte[] bytes = new byte[(int)len];
BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(file));
int r = bufferedInputStream.read( bytes );
if (r != len)
throw new IOException("讀取文件不正確");
bufferedInputStream.close();
return bytes;
}
/**
* 將數(shù)據(jù)寫入文件
* @param data byte[]
* @throws IOException
*/
public static void writeFile(byte[] data,String filename) throws IOException {
File file =new File(filename);
file.getParentFile().mkdirs();
BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(file));
bufferedOutputStream.write(data);
bufferedOutputStream.close();
}
/**
* 從jar文件里讀取class
* @param filename String
* @throws IOException
* @return byte[]
*/
public byte[] readFileJar(String filename) throws IOException {
BufferedInputStream bufferedInputStream=new BufferedInputStream(getClass().getResource(filename).openStream());
int len=bufferedInputStream.available();
byte[] bytes=new byte[len];
int r=bufferedInputStream.read(bytes);
if(len!=r)
{
bytes=null;
throw new IOException("讀取文件不正確");
}
bufferedInputStream.close();
return bytes;
}
/**
* 讀取網(wǎng)絡(luò)流,為了防止中文的問題,在讀取過程中沒有進行編碼轉(zhuǎn)換,而且采取了動態(tài)的byte[]的方式獲得所有的byte返回
* @param bufferedInputStream BufferedInputStream
* @throws IOException
* @return byte[]
*/
public byte[] readUrlStream(BufferedInputStream bufferedInputStream) throws IOException {
byte[] bytes = new byte[100];
byte[] bytecount=null;
int n=0;
int ilength=0;
while((n=bufferedInputStream.read(bytes))>=0)
{
if(bytecount!=null)
ilength=bytecount.length;
byte[] tempbyte=new byte[ilength+n];
if(bytecount!=null)
{
System.arraycopy(bytecount,0,tempbyte,0,ilength);
}
System.arraycopy(bytes,0,tempbyte,ilength,n);
bytecount=tempbyte;
if(n<bytes.length)
break;
}
return bytecount;
}
}