How to avoid getting URL encoded paths from URL.getFile()?

前端 未结 2 531
故里飘歌
故里飘歌 2021-01-17 20:22

I\'m having the following problem when trying to get the path of a given resource:

    System.out.println(\"nf=\"+new File(\".\").getAbsolutePath());      
          


        
相关标签:
2条回答
  • 2021-01-17 20:46

    This is due to a URL handling quirk in the API. You can work around this by converting the URL string to a URI first:

    new URI(this.getClass().getResource(".").toString()).getPath()
    

    This will produce a String as follows:

    "C:\Users\current user\workspace\xyz\bin\something"
    
    0 讨论(0)
  • 2021-01-17 20:51

    I'm adding Mr_Thorynque comment as an answer as it also works and at least for me seems to be simpler.

    this.getClass().getResource(".").toURI().getPath()
    
    0 讨论(0)
提交回复
热议问题