`

复制文件/文件夹,删除文件/文件夹

阅读更多

复制文件夹:

public static boolean copyFolder(String srcFolderFullPath, String destFolderFullPath) {
        try {
            (new File(destFolderFullPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
            File file = new File(srcFolderFullPath);
            String[] files = file.list();
            File temp = null;
            for (int i = 0; i < files.length; i++) {
                if (srcFolderFullPath.endsWith(File.separator)) {
                    temp = new File(srcFolderFullPath + files[i]);
                } else {
                    temp = new File(srcFolderFullPath + File.separator + files[i]);
                }
                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    copyFile(input, destFolderFullPath + "/" + (temp.getName()).toString());
                }
                if (temp.isDirectory()) {// 如果是子文件夹
                    copyFolder(srcFolderFullPath + "/" + files[i], destFolderFullPath + "/" + files[i]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

 复制文件:

public static boolean copyFile(InputStream ins, String destFileFullPath) {
        FileOutputStream fos = null;
        try {
            File file = new File(destFileFullPath);
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[8192];
            int count = 0;
            while ((count = ins.read(buffer)) > 0) {
                fos.write(buffer, 0, count);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                fos.close();
                ins.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 删除文件:

public static void deleteFile(String targetFileFullPath) {
        File file = new File(targetFileFullPath);
        file.delete();
    }

 删除文件夹:

public static void deleteFolder(String targetFolderFullPath) {
        File file = new File(targetFolderFullPath);
        if (!file.exists()) {
            return;
        }
        String[] files = file.list();
        File temp = null;
        for (int i = 0; i < files.length; i++) {
            if (targetFolderFullPath.endsWith(File.separator)) {
                temp = new File(targetFolderFullPath + files[i]);
            } else {
                temp = new File(targetFolderFullPath + File.separator + files[i]);
            }
            if (temp.isFile()) {
                deleteFile(targetFolderFullPath + "/" + (temp.getName()).toString());
            }
            if (temp.isDirectory()) {// 如果是子文件夹
                deleteFolder(targetFolderFullPath + "/" + files[i]);
            }
        }
    }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics