java以字节流形式读写文件

来源:互联网 发布:淘宝的子账号怎么设置 编辑:程序博客网 时间:2024/05/28 17:05
java中以字节流的形式读取文件采用的是FileInputStream,将指定路径的文件以字节数组的形式循环读取,代码如下:
public void ReadFileByByte(String path){try {int length = 0;byte[] Buff = new byte[1024];File file = new File(path);FileInputStream fis = new FileInputStream(file);while((length =fis.read(Buff))!=-1){//对Buff进行处理} } catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch (IOException ex) {// TODO Auto-generated catch blockex.printStackTrace();}finally{
if(fis!=null){
fis.close();
}
}}

java中以字节流的形式写入文件采用的是FileOutputStream,在指定路径下写入指定字节数组内容,并可设定追加模式或者覆盖模式,代码如下:

public void WriteFileByByte(String path,byte[] contents,boolean isAppend){try {int length = contents.length;FileOutputStream fos = new FileOutputStream(path,isAppend);//isAppend如果为true,为追加写入,否则为覆盖写入fos.write(contents,0,length);//表示把字节数组contents的从下标0开始写入length长度的内容 } catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch (IOException ex) {// TODO Auto-generated catch blockex.printStackTrace();}finally{
if(fos!=null){
fos.close();
}
}
}


原创粉丝点击