我正在尝试使用相对路径的组合将 .txt 文件加载到 java 中的 arrayList 中。 我的 jar 文件位于/usr/tool/dist/tool.jar 我要加载的文件位于/usr/tool/files/file.txt
我认为我能够检索 tool.jar 的路径,但如何从该路径转到我的文件所在的路径?
我有以下代码
// String path should give me '/usr/tool'
File f = new File(System.getProperty("java.class.path"));
File dir = f.getAbsoluteFile().getParentFile();
String path = dir.toString();
String table1 = this should represent /usr/tool/files/file.txt
BufferedReader buf_table1 = new BufferedReader(new FileReader(new File(table1)));
最佳答案
要查找正在执行的 jar
文件的路径,java.class.path
不是正确的属性。该属性可能包含多个文件,并且您无法知道哪一个是正确的。 (See the docs.)
要查找正确的 jar 文件的路径,您可以使用以下命令:
URL url = MainClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
其中 MainClass
是工具的主类,或同一 jar 文件中的任何其他类。
接下来,文件的父File
是它的目录。因此,/usr/tool/dist/tool.jar
的父File
是/usr/tool/dist/
。因此,如果您想访问 /usr/tool/files/file.txt
,您需要获取父级的父级,然后从那里 files/file.txt
>.
放在一起:
File jarFile = new File(MainClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
File file = new File(jarFile.getParentFile().getParent(), "files/file.txt");
关于java - 如何打开与应用程序的.jar文件位于同一目录中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40317459/