Home > Software engineering >  Java: Possible to name a path with exactly 1 unknown directory?
Java: Possible to name a path with exactly 1 unknown directory?

Time:01-24

Lets say I have a directory-structure.

/a/b/c/<unknown name>/d/e/f/<files>

for Windows:

C:\a\b\c\<unknown name>\d\e\f<files>

I know a/b/c is always there and also d/e/f/.

I do not know the directory () between them but I know there is only 1.

Is there a way in Java I can name this path without finding out the name of the 1 unknown directory to access ??

Like so?

/a/b/c/*/d/e/f

CodePudding user response:

Lets say you have a dockerized app based on a linux distribution.

You can run this unix command: find . -name d/e/f/yourFilename using Process Builder

This will return the complete filepath to your file which will include the unknown portion. And then you can assign it to a String and use in your Java app.

CodePudding user response:

Yes, it is possible but probably not as straightforward as you think, you'd use the Files.walk method like follows:

    Path root = Paths.get("S:\\Coding\\");

    String prefix = "A\\AB";
    String suffix = "B\\C";
    
    Path searchRoot = root.resolve(prefix);
    
    System.err.println(searchRoot);
    
    List<Path> paths = Files.walk(searchRoot).filter(f -> f.endsWith(suffix)).collect(Collectors.toList());
    
    paths.forEach(System.out::println);

Outputs:

stderr: S:\Coding\A\AB
stdout: S:\Coding\A\AB\ZZZ\B\C

CodePudding user response:

You can hardcode your search method as indicated in other answers. Or, to stay flexible match against patterns. You would need some pattern language to specify your path:

  • Shells typically use globbing.
  • Alternatively you could use regexp to distinguish wanted from unwanted files.

Once you have such a pattern matcher, use a tree walking algorithm (traverse the directory structure recursively), match each absolute path name with your pattern. If it matches, perform some action.

Be aware some globbing seems to exist in Java - see Match path string using glob in Java

  •  Tags:  
  • java
  • Related