JAVA将文件复制到指定的文件夹中(源码)

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

 

public class CreateAbsolutePathFile {

  public static void main(String[] args) throws IOException {

    if (args.length < 1)

      return;

    String firstPath = args[0];

    String beCopiedFilePath = args[1];

 

    File file = new File(firstPath);

 

//如果复制到的文件夹没有则创建

    if (!file.exists()) {

      file.mkdirs();

    } else if (beCopiedFilePath != null && beCopiedFilePath.length() > 0) {

      copyFile(beCopiedFilePath, firstPath);

    }

  }

 

  public static void copyFile(String oldPathFile, String newPathFile) {

    int byteread = 0;

    int byteCount = 0;

    File oldfile = new File(oldPathFile);

//用spilit方法实际是在用正则表达式进行匹配,java中//由于转义符代表为/,所以实际为//,又在正则表达式中//代表/所以表示/

//而在不需要正则表达式的方法如String的replace则可以用//表示/这点需要注意

    String[] fileName = oldPathFile.split("");

    String name = fileName[fileName.length - 1];

    boolean isSuccessful = true;

    if (oldfile.exists()) { // 文件存在时

      try {

        InputStream inStream = new FileInputStream(oldPathFile); // 读入原文件

        BufferedInputStream bufferedInputStream = new BufferedInputStream(inStream);

 

//复制到的文件必须是具体的文件不能是文件夹,如果为文件夹则出现拒绝访问的异常,所以加上name

        FileOutputStream fs = new FileOutputStream(newPathFile + "//" + name);

        BufferedOutputStream bufferedOutPutStream = new BufferedOutputStream(fs);

 

        byte[] buffer = new byte[1024 * 5];

        while ((byteread = bufferedInputStream.read(buffer)) != -1) {

          byteCount += byteread;

          bufferedOutPutStream.write(buffer, 0, byteread);

        }

        inStream.close();

        bufferedInputStream.close();

        fs.close();

        bufferedOutPutStream.close();

      } catch (IOException e) {

        System.out.println("读取文件出错!原因" + e.getMessage());

        isSuccessful = false;

      }

    } else {

      System.out.println("地址" + oldPathFile + "不存在文件");

      isSuccessful = false;

    }

    if (isSuccessful)

      System.out.println("复制成功!共复制" + byteCount + "字节");

  }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值