我正在尝试使用相对路径的组合将.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
不是正确的属性。此属性可能包含多个文件,并且您不知道哪个是正确的文件。(请参阅文档。)
要找到正确的jar文件的路径,可以改用以下代码:
URL url = MainClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
当MainClass
主类的工具,或者在同一个jar文件中的任何其他类。
接下来,File
文件的父目录是其目录。因此,的父File
项/usr/tool/dist/tool.jar
是/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");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句