有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (6) 个答案

  1. # 1 楼答案

    File f = new File("C:/aaa/bbb/ccc/ddd/test.java");
    System.out.println(f.getParentFile().getName())
    

    f.getParentFile()可以为空,因此您应该检查它

  2. # 2 楼答案

    在下面使用

    File file = new File("file/path");
    String parentPath = file.getAbsoluteFile().getParent();
    
  3. # 3 楼答案

    如果您只有字符串路径,并且不想创建新的文件对象,则可以使用以下方法:

    public static String getParentDirPath(String fileOrDirPath) {
        boolean endsWithSlash = fileOrDirPath.endsWith(File.separator);
        return fileOrDirPath.substring(0, fileOrDirPath.lastIndexOf(File.separatorChar, 
                endsWithSlash ? fileOrDirPath.length() - 2 : fileOrDirPath.length() - 1));
    }
    
  4. # 4 楼答案

    File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
    File curentPath = new File(file.getParent());
    //get current path "C:/aaa/bbb/ccc/ddd/"
    String currentFolder= currentPath.getName().toString();
    //get name of file to string "ddd"
    

    如果需要通过另一个路径附加文件夹“ddd”,请使用

    String currentFolder= "/" + currentPath.getName().toString();
    
  5. # 5 楼答案

    自Java7以来,您有了新的Paths api。最现代、最清洁的解决方案是:

    Paths.get("C:/aaa/bbb/ccc/ddd/test.java").getParent().getFileName();
    

    结果将是:

    C:/aaa/bbb/ccc/ddd
    
  6. # 6 楼答案

    使用^{}'s ^{} methodString.lastIndexOf()检索直接父目录

    马克的评论是比lastIndexOf()更好的解决方案:

    file.getParentFile().getName();
    

    这些解决方案仅在文件具有父文件时有效(例如,通过采用父文件File的一个文件构造函数创建)。当getParentFile()为空时,您需要使用lastIndexOf,或者使用类似Apache Commons' ^{}的内容:

    FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());
    => C:/aaa/bbb/ccc/ddd
    

    有几种变体可以保留/删除前缀和尾随分隔符。您可以使用相同的FilenameUtils类从结果中获取名称,也可以使用lastIndexOf