现在的位置: 首页 > 综合 > 正文

Java删除文件夹 及目录下 文件 递归操作

2018年02月11日 ⁄ 综合 ⁄ 共 2471字 ⁄ 字号 评论关闭

public class FileOpeUtil {

    public static void main(String[] args) throws IOException {
        // delAllFiles("C://Users/13075012/.swt/");
        String s = "D://opt/opt/ds.json";
        /*
         * String name1 = s.substring(0,s.lastIndexOf("/")+1); System.out.println(name1); String name =
         * s.substring(s.lastIndexOf("/")+1); System.out.println(name); File f = new File(name1); if(!f.exists()){
         * f.mkdirs(); }
         */

        File f2 = new File(s);
        System.out.println(f2.createNewFile());
    }

    public static void dealWithDir(String prefixPath, String lockerCode, boolean flag) {
        delAllFiles(prefixPath);
        if (flag) {
            File file = new File(prefixPath + lockerCode);
            file.mkdir();
        }

    }

    private static void delAllFiles(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.delete()) {
            delAllFolders(file.getPath());
        } else {
            file.delete();
        }

    }

    private static void delAllFolders(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                delAllFiles(f.getPath());
                delAllFolders(f.getPath());
                f.delete();
            }
        }
        if (file.isFile()) {
            file.delete();
        }
    }

}

 

============================================

String absolutePath = request.getSession().getServletContext()
                    .getRealPath(File.separator + "software" + File.separator + "updatelist.json");
            File jsonFile = new File(absolutePath);
            if (!jsonFile.exists()) {
                String absuluDir = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator) + 1);

                File dirFile = new File(absuluDir);
                if (!dirFile.exists()) {
                    dirFile.mkdirs();
                }
                jsonFile.createNewFile();
            }

            br = new BufferedReader(new InputStreamReader(new FileInputStream(jsonFile)));
            while ((line = br.readLine()) != null) {
                stringBuffer.append(line);
            }
            JSONObject jsonObj = JsonFileUtil.dealWithUpdate(stringBuffer.toString(), lockerCode, delFlag,
                    orginFileName);
            // 将json数据再次写入文件

            bw = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(new File(
                    absolutePath)))));
            bw.write(jsonObj.toString());
            bw.flush();// 强制将缓冲区 写入

 

抱歉!评论已关闭.