下面直接写代码,每次从文件中读取1M数据,循环读取
第一种方式
public byte[]readByte(String filePaht) throws Exception{
File file=new File(filePaht);
BufferedInputStream binput=null;
if(!file.exists())
throw new Exception("sorry ,can not read unexists file");
FileInputStream finput=new FileInputStream(file);
binput=new BufferedInputStream(finput);
binput=new BufferedInputStream(finput);
byte[] temp=new byte[1024];
byte[] result = new byte[1024];
int t=0;
int flit=0;
while((t=binput.read(temp))!=-1){
System.arraycopy(temp, 0, result, flit, t);
flit=t;
result=Arrays.copyOf(result, t+1024);
}
return result
}
第二种方式
public void read(String filePaht) throws Exception{
File file=new File(filePaht);
BufferedInputStream binput=null;
if(!file.exists())
throw new Exception("sorry ,can not read unexists file");
FileInputStream finput=new FileInputStream(file);
binput=new BufferedInputStream(finput);
byte[] temp=new byte[1024];
StringBuffer sb=new StringBuffer();
int tt=0;
while( (tt=binput.read(temp))!=-1){
sb.append(new String(temp,"GBK"));
}
}
说白了,第一种就是创建两个byte数组,一个临时数组,一个结果数组,然后不断的给结果数组扩容,避免在不知道文件具体大小时为起始容量发愁;第二种唯一不同在于通过StringBuffer绑定临时数组的数据,结果读出来肯定是一样的
本文展示了两种在Java中读取文件的方法:使用字节数组循环读取并扩容,以及利用StringBuffer逐块转换为字符串。第一种方式避免了预估文件大小的问题,而第二种则通过字符串拼接实现。两种方法最终都能得到相同的结果。
1632

被折叠的 条评论
为什么被折叠?



