java 文件封装_Java字节流文件封装

/*** 字节流封装方法*/

importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;public classFileUtilStream {//

public staticString readFile(String path){

StringBuffer sb=newStringBuffer();//1.创建文件的字节流

InputStream fis=null;try{

fis=new FileInputStream(path);//InputStream为抽象类,不能实例化

byte [] bytes=new byte[1024];//数组

int data=0;while ((data=fis.read(bytes))!=-1) {//(data=fis.read(bytes))!=-1表示读到最后了//字符串的转换

String str=new String(bytes,0,data);//后面加,0,data是防止1024出现0000000

sb.append(str);

}

}catch(Exception e) {

e.printStackTrace();

}finally{//2.关闭字节流

try{if (fis!=null) {

fis.close();

}

}catch(IOException e) {

e.printStackTrace();

}

}returnsb.toString();

}//

public static boolean writeFile(String path,String content,booleanflag){boolean result=false;//1.创建文件的字节流

OutputStream fos=null;try{//2.创建 输出流对象

fos=new FileOutputStream(path, flag);//flag表示是否覆盖,flag=true表示在末尾添加,flag=false表示覆盖//字符串String--->byte[]

byte[] words=content.getBytes();//写入

fos.write(words, 0, words.length);

result=true;

}catch(Exception e) {

}finally{try{if (fos!=null) {

fos.close();

}

}catch(IOException e) {

e.printStackTrace();

}

}returnresult;

}//

public static booleancopyFile(String frompath,String toPath){boolean result=false;//文件的复制:先读取要复制的文件,再写入新文件//1.读取文件

InputStream fis=null;//2.写入文件

OutputStream fos=null;try{//3.读取

fis=newFileInputStream(frompath);//4.写入

fos=newFileOutputStream(toPath);//5.边读边写

StringBuffer content=newStringBuffer();//【读】

byte [] bytes=new byte[1024];//数组

int data=0;while ((data=fis.read(bytes))!=-1) {//(data=fis.read(bytes))!=-1表示读到最后了//字符串的转换

String str=new String(bytes,0,data);//后面加,0,data是防止1024出现0000000

content.append(str);

}//【写】//字符串String--->byte[]

byte[] words=content.toString().getBytes();//写入

fos.write(words, 0, words.length);

result=true;

}catch(Exception e) {

}finally{try{if (fis!=null) {

fis.close();

}if (fos!=null) {

fos.close();

}

}catch(IOException e) {

e.printStackTrace();

}

}returnresult;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值