java 剪切

来源:互联网 发布:中老年女雪地靴淘宝 编辑:程序博客网 时间:2024/04/29 21:20

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;    }}