java - 如何删除目录中的所有文件但保留符号链接(symbolic link)指向的文件?

标签 java

这已被确定为可能与此处的另一个问题重复,但事实并非如此。我知道如何删除符号链接(symbolic link)和文件。我试图保留与符号链接(symbolic link)关联的文件,但删除其他所有内容。

我的问题:删除目录中超过 7 天的所有文件,与符号链接(symbolic link)关联的文件除外。

问题:符号链接(symbolic link)已成功删除,但剩余的旧文件未删除。

详细信息:我正在尝试编写一个简单的 Java 程序来删除超过 7 天的目录中的所有文件和子文件夹,该程序可以工作,但有一个问题。如果存在符号链接(symbolic link),那么我需要仅删除该链接并保留它链接到的文件。除此情况外,其他所有内容都会被删除。我知道我非常接近...如果您有任何建议请告诉我。目前,我可以让它删除符号链接(symbolic link),但其他旧文件在应该删除的时候却没有被删除。这可能是一个简单的逻辑错误,也可能是我处理问题的方式错误。提前致谢!


import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class delcache {

    public static void main(String[] args) throws IOException
    {
        String path1="/home/test/cachetest";
        recursiveDelete(7, path1);
    }

    public static void recursiveDelete(int days, String dirPath) throws IOException {

        long cutOff = System.currentTimeMillis() - (days * 24 * 60 * 60 * 1000);
        Files.list(Paths.get(dirPath))
        .forEach(path -> {
            if (Files.isDirectory(path)) {
                try {
                    recursiveDelete(days, path.toString());
                } catch (IOException e) {
                    // log
                }
            } else {
                try {

                    if (Files.getLastModifiedTime(path).to(TimeUnit.MILLISECONDS) < cutOff) {

                        String pathsave = null;

                        if(Files.isSymbolicLink(path)) {
                            pathsave = path.toRealPath().toString();
                            System.out.println("pathsave: " + pathsave);
                            System.out.println("delete symlink: " + path);
                            Files.delete(path);
                        }


                        if(!(Files.isSymbolicLink(path))) {

                            System.out.println("pathsave: " + pathsave);
                            if(!(path.toString().equals(pathsave))) {
                                System.out.println("not equal so delete file: " + path);
                                Files.delete(path);
                            }



                        }

                        //Files.delete(path);

                    }
                } catch (IOException ex) {
                    // log
                }
            }
        });
    }


}

最佳答案

您的逻辑有缺陷,String pathsave 仅在特定路径的当前循环中持续存在。当循环到达实际文件时,pathsave 始终为空。
如果你想保存符号链接(symbolic link)路径,你需要有一个函数外部的路径列表。即使这样它也不会工作,因为你不能保证任何顺序,你可能首先到达符号链接(symbolic link)或首先到达文件。

因此,据我了解,您必须首先迭代文件夹查找所有符号链接(symbolic link),将它们保存到该方法可访问的全局 List 中,然后运行并删除文件。
旁注:请注意,如果删除符号链接(symbolic link),下次运行此函数时,以前具有符号链接(symbolic link)的相同文件现在将被删除

public static void main(String[] args) throws IOException
{
    String path1="/home/test/cachetest";
    List<Path> symlinks = getAllSymLinks(path1);
    recursiveDelete(7, path1, symlinks);
}

public static List<Path> getAllSymLinks(String dirPath) throws IOException {
        List<Path> paths = new ArrayList<>();
        Files.list(Paths.get(dirPath))
        .forEach(path -> {
            if (Files.isDirectory(path)) {
                try {
                    paths.addAll(recursiveDelete(days, path.toString()));
                } catch (IOException e) {
                    // log
                }
            } else {
                try {
                    if(Files.isSymbolicLink(path)) {
                        paths.add(path.toRealPath());
                    }
                } catch (IOException ex) {
                    // log
                }
            }
        });

        return paths;
}

public static void recursiveDelete(int days, String dirPath, List<path> symlinks) throws IOException {
    long cutOff = System.currentTimeMillis() - (days * 24 * 60 * 60 * 1000);
    Files.list(Paths.get(dirPath))
    .forEach(path -> {
        if (Files.isDirectory(path)) {
          try {
              recursiveDelete(days, path.toString(), symlinks);
          } catch (IOException e) {
            // log
          }
        } 
        else {
          try {
            if (Files.getLastModifiedTime(path).to(TimeUnit.MILLISECONDS) < cutOff &&
                !Files.isSymbolicLink(path) &&
                !symlinks.contains(path)) 
            {
                 Files.delete(path);    
            }
          } catch (IOException ex) {
            // log
          }
        }
    });

关于java - 如何删除目录中的所有文件但保留符号链接(symbolic link)指向的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55975757/

相关文章:

java - 如何在 xml 标记之间提取多语言字符串

java - 添加到 arraylist 意外行为

java - 微调器所选项目出现 NullpointerException 错误

java - AQL-在 Arangodb 中可以实现预期连接以及如何实现?

java - Hibernate 查询中的 Oracle 存储过程执行

java - 执行线程核心数

java - 构建安卓应用 :I can sending data to database in localhost but not the same in online database

java - XmlSerializer.setProperty 抛出异常

java - java中如何获取特定长度的字符串

java - 如何设置字符串(HH :mm) to UTC time with current date and convert it to local time