java 剪切


java 剪切

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
* Java实现文件复制、剪切、删除操作
* 文件指文件或文件夹
* 文件分割符统一用"\\"
*/

public class FileDemo {
    
public static void main(String[] args) {
  isExist("F:\\1\\h.txt");
}
/**
  *
  * @param path 文件夹路径
  */
public static void isExist(String path) {
  File file = new File(path);
  //判断文件夹是否存在,如果不存在则创建文件夹
  if (!file.exists()) {
   //file.mkdir();
   System.out.println("文件夹不存在!!");
  }else{
       System.out.println("文件夹存在!");
         cutGeneralFile("F:\\1\\h.txt", "F:\\1\\2");
       }
}

     /**
     * 复制文件到目标目录
     * @param srcPath
     *            源文件绝对路径
     * @param destDir
     *            目标文件所在目录
     * @param overwriteExistFile
     *            是否覆盖目标目录下的同名文件
     * @return boolean
     */
    public static boolean copyFile(String srcPath, String destDir) {
        boolean flag = false;

        File srcFile = new File(srcPath);
        if (!srcFile.exists() || !srcFile.isFile()) { // 源文件不存在
            return false;
        }
       
        //获取待复制文件的文件名
        String fileName = srcFile.getName();
        String destPath = destDir + File.separator +fileName;
        File destFile = new File(destPath);
        
        File destFileDir = new File(destDir);
        if(!destFileDir.exists() && !destFileDir.mkdirs()) {     // 目录不存在并且创建目录失败直接返回
             return false;
        }
       
        try {
            FileInputStream fis = new FileInputStream(srcPath);
            FileOutputStream fos = new FileOutputStream(destFile);
            byte[] buf = new byte[1024];
            int c;
            while ((c = fis.read(buf)) != -1) {
                fos.write(buf, 0, c);
            }
            fos.flush();
            fis.close();
            fos.close();

            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return flag;
    }
   
       /**
     * 删除文件或文件夹
     * @param path
     *            待删除的文件的绝对路径
     * @return boolean
     */
    public static boolean deleteFile(String path) {
        boolean flag = false;

        File file = new File(path);
        if (!file.exists()) { // 文件不存在直接返回
            return flag;
        }

        flag = file.delete();

        return flag;
    }
   
        /**
     * 由上面方法延伸出剪切方法:复制+删除
     * @param  destDir 同上
     */
    public static boolean cutGeneralFile(String srcPath, String destDir) {
         boolean flag = false;
        if(copyFile(srcPath, destDir) && deleteFile(srcPath)) { // 复制和删除都成功
             flag = true;
        }
       
        return flag;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值