java document元素复制_java实现File的拷贝(Document learning —five)

1. 通过字节流实现文件的拷贝

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

/*** 通过字节流实现文件的拷贝

*@paramsourcePath 源文件路径

*@paramtargetPath 目标文件路径*/

public static voidcopyFileByStream(String sourcePath,String targetPath){//源文件路径

File source = newFile(sourcePath);//目标文件路径

File target = newFile(targetPath);//如果源文件不存在则不能拷贝

if(!source.exists()){return;

}//如果目标文件目录不存在则创建

if(!target.getParentFile().exists()){

target.getParentFile().mkdirs();

}try{//实现文件的拷贝

InputStream inputStream = newFileInputStream(source);

OutputStream outputStream= newFileOutputStream(target);int temp = 0;//每次读取1024个字节

byte[] data = new byte[1024];//将每次读取的数据保存到字节数组里面,并且返回读取的个数

while ((temp = inputStream.read(data)) != -1){//输出数组

outputStream.write(data,0,temp);

}

inputStream.close();

outputStream.close();

}catch(IOException e) {

e.printStackTrace();

}

}

View Code

2. 通过字符流实现文件拷贝(使用字符流只能拷贝文本文件)

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

/*** 通过字符流实现文件的拷贝

*

*@paramsourcePath 源文件路径

*@paramtargetPath 目标文件路径*/

public static voidcopyFileByReaderAndWriter(String sourcePath, String targetPath) {//源文件路径

File source = newFile(sourcePath);//目标文件路径

File target = newFile(targetPath);//如果源文件不存在则不能拷贝

if (!source.exists()) {return;

}//如果目标文件目录不存在则创建

if (!target.getParentFile().exists()) {

target.getParentFile().mkdirs();

}

FileReader in= null;

FileWriter out= null;try{//字符输入流和字符输出流

in = newFileReader(source);

out= newFileWriter(target);char[] c = new char[1024];int temp = 0;//每次读取1024个字符

while ((temp = in.read(c)) != -1) {//输出到文件

out.write(c, 0, temp);

}

}catch(IOException e) {

e.printStackTrace();

}finally{//关闭流

try{if (in != null) {

in.close();

}if (out != null) {

out.close();

}

}catch(IOException e) {

e.printStackTrace();

}

}

}

View Code

3. 通过字节缓冲流实现文件拷贝

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

/*** 通过字节缓冲流实现文件的拷贝

*

*@paramsourcePath 源文件路径

*@paramtargetPath 目标文件路径*/

public static voidcopyFileByBuffered(String sourcePath, String targetPath){//源文件路径<

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值