Home > Enterprise >  How to get file path after certain directory in java
How to get file path after certain directory in java

Time:12-29

Let's say given file path is below

D:\data\test\html\css\Core.css

Expectation

  1. I want to get file path after /html

Output: /css/Core.css

  1. I want to get file path after /test

Output: /html/css/Core.css

Didn't find anything to get path after certain directory.

CodePudding user response:


    import java.io.File;
    
    public class Main {
      public static void main(String[] args) {
        // Create a File object for the directory that you want to start from
        File directory = new File("/path/to/starting/directory");
    
        // Get a list of all files and directories in the directory
        File[] files = directory.listFiles();
    
        // Iterate through the list of files and directories
        for (File file : files) {
          // Check if the file is a directory
          if (file.isDirectory()) {
            // If it's a directory, recursively search for the file
            findFile(file, "target-file.txt");
          } else {
            // If it's a file, check if it's the target file
            if (file.getName().equals("target-file.txt")) {
              // If it's the target file, print the file path
              System.out.println(file.getAbsolutePath());
            }
          }
        }
      }
    
      public static void findFile(File directory, String targetFileName) {
        // Get a list of all files and directories in the directory
        File[] files = directory.listFiles();
    
        // Iterate through the list of files and directories
        for (File file : files) {
          // Check if the file is a directory
          if (file.isDirectory()) {
            // If it's a directory, recursively search for the file
            findFile(file, targetFileName);
          } else {
            // If it's a file, check if it's the target file
            if (file.getName().equals(targetFileName)) {
              // If it's the target file, print the file path
              System.out.println(file.getAbsolutePath());
            }
          }
        }
      }
    }

This code uses a recursive function to search through all subdirectories of the starting directory and print the file path of the target file (in this case, "target-file.txt") if it is found.

You can modify this code to suit your specific needs, such as changing the starting directory or target file name. You can also modify the code to perform different actions on the target file, such as reading its contents or copying it to another location.

CodePudding user response:

If you only need the path in the form of a string another solution would be to use this code:

String path = "D:\\data\\test\\html\\css\\Core.css";
String keyword = "\\html";

System.out.println(path.substring(path.lastIndexOf(keyword)   keyword.length()).trim());

You can replace the path with file.getAbsolutePath() as mentioned above.

CodePudding user response:

Your question lacks details.

  • Is the "path" a Path or a String?
  • How do you determine which part of the "path" you want?
  • Do you know the entire structure of the "path" or do you just have the delimiting part, for example the html?

Here are six different ways (without iterating, as you stated in your comment). The first two use methods of java.nio.file.Path. The next two use methods of java.lang.String. The last two use regular expressions. Note that there are probably also other ways.

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PathTest {

    public static void main(String[] args) {
        // D:\data\test\html\css\Core.css
        Path path = Paths.get("D:", "data", "test", "html", "css", "Core.css");
        System.out.println("Path: "   path);
        Path afterHtml = Paths.get("D:", "data", "test", "html").relativize(path);
        System.out.println("After 'html': "   afterHtml);
        System.out.println("subpath(3): "   path.subpath(3, path.getNameCount()));
        String str = path.toString();
        System.out.println("replace: "   str.replace("D:\\data\\test\\html\\", ""));
        System.out.println("substring: "   str.substring(str.indexOf("html")   5));
        System.out.println("split: "   str.split("\\\\html\\\\")[1]);
        Pattern pattern = Pattern.compile("\\\\html\\\\(.*$)");
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
            System.out.println("regex: "   matcher.group(1));
        }
    }
}

Running the above code produces the following output:

Path: D:\data\test\html\css\Core.css
After 'html': css\Core.css
subpath(3): css\Core.css
replace: css\Core.css
substring: css\Core.css
split: css\Core.css
regex: css\Core.css

I assume you know how to modify the above in order to

I want to get file path after /test

  •  Tags:  
  • java
  • Related