Convert a classpath filename to a real filename

后端 未结 1 1633
悲哀的现实
悲哀的现实 2021-01-02 00:02

How would I convert the name of a file on the classpath to a real filename?

For example, let\'s say the directory \"C:\\workspace\\project\\target\\classes\"

相关标签:
1条回答
  • 2021-01-02 00:25

    Use a combination of ClassLoader.getResource() and URL.getFile()

    URL url = Thread.currentThread().getContextClassLoader().getResource( resource );
    if( url == null ){
        throw new RuntimeException( "Cannot find resource on classpath: '" + resource + "'" );
    }
    String file = url.getFile();
    

    Note for Windows: in the example above, the actual result will be

    "/C:/workspace/project/target/classes/info.properties"
    

    If you need a more Windows-like path (i.e. "C:\workspace\..."), use:

    String nativeFilename = new File(file).getPath();
    
    0 讨论(0)
提交回复
热议问题