获取java文件相对路径
时间: 2024-10-31 09:04:33 浏览: 40
在Java中,获取当前运行程序文件的相对路径通常通过ClassLoader
或File
类配合使用来实现。以下是一些示例:
基于Class类:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL resource = classLoader.getResource("yourFile.java"); // 替换为你的文件名 File file = new File(resource.getFile()); String relativePath = file.getAbsolutePath().substring(file.getCanonicalPath().length() + 1);
这里
getResources()
方法返回一个URL数组,表示类加载器能够找到的所有资源。从URL的getFile()
方法得到的是绝对路径,然后减去根目录的部分得到相对路径。基于File类:
File currentDirectory = new File("."); File yourFile = new File(currentDirectory, "yourFile.java"); // 替换为你的文件名 String relativePath = yourFile.getAbsolutePath().substring(currentDirectory.getAbsolutePath().length() + 1);
这种方式假设你的文件位于当前目录下,如果是其他位置,需要相应调整。
请注意,以上方法可能会因为JVM启动环境的不同而略有差异,比如打包成jar文件时,可能需要使用getResourceAsStream()
来获取InputStream然后再转换。
相关推荐


















