Get the filePath from Filename using Java

后端 未结 5 924
日久生厌
日久生厌 2021-01-04 05:33

Is there a easy way to get the filePath provided I know the Filename?

相关标签:
5条回答
  • 2021-01-04 06:19

    You can use the Path api:

    Path p = Paths.get(yourFileNameUri);
    Path folder = p.getParent();
    
    0 讨论(0)
  • 2021-01-04 06:20

    I'm not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:

    System.out.println("File path: " + new File("Your file name").getAbsolutePath());
    

    The File class has several more methods you might find useful.

    0 讨论(0)
  • 2021-01-04 06:22

    Correct solution with "File" class to get the directory - the "path" of the file:

    String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();
    

    which will return:

    path = "C:\\Temp\\your directory"
    
    0 讨论(0)
  • 2021-01-04 06:30

    Look at the methods in the java.io.File class:

    File file = new File("yourfileName");
    String path = file.getAbsolutePath();
    
    0 讨论(0)
  • 2021-01-04 06:35

    You may use:

    FileSystems.getDefault().getPath(new String()).toAbsolutePath();
    

    or

    FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()
    

    This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.

    Example: /src/main/java...

    0 讨论(0)
提交回复
热议问题