如何把一个本地文件读到一个byte[]数组里面去?

keikai 2002-11-12 10:58:00
难道要自己先设定一个bufferSize,再读???buffersize不够的时候,再重新分配?有没有现成的方法?
...全文
105 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
qxjavajava 2002-11-12
  • 打赏
  • 举报
回复
import java.io.*;
class Example20_1
{ public static void main(String args[])
{ int b;
byte buffer[]=new byte[2500];//-------------here ..当然你可以设的大一些,恰到好处,更有价值。
try{ FileInputStream readfile=new FileInputStream("Example211.java");
b=readfile.read(buffer,0,2500);
try { String str=new String(buffer,0,b,"Default");
System.out.println(str);
}
catch(UnsupportedEncodingException e)
{ System.out.println(" the encoding was not found:"+e);
}
}
catch(IOException e)
{System.out.println("File read Error ");
}
}
}
tomxutomxu 2002-11-12
  • 打赏
  • 举报
回复
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[256];
int l;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((l=fis.read(b)) != -1){
bos.write(b,0,l);
}
fis.close();
return bos.toByteArray();
tomxutomxu 2002-11-12
  • 打赏
  • 举报
回复
用FileInputStream 读文件,
写入ByteArrayOutputStream
再获得byte[]

fastmask 2002-11-12
  • 打赏
  • 举报
回复
没有的,你只能先获取文件长度,然后new这么大空间,然后读

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧