从放置 jar 文件的特定目录中获取文件 [英] Fetch file from specific directory where jar file is placed

查看:50
本文介绍了从放置 jar 文件的特定目录中获取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的 jar 文件所在的目录中获取一个文本文件.

I want to fetch a text file from the directory where my jar file is placed.

假设我的桌面应用程序 'foo.jar' 文件放在 Windows 安装中的 d:\ 中.在foo.jar"应用程序运行时,我想在同一目录中读取一个 test.txt 文件.如何在我的foo.jar"应用程序中获取该特定路径?简而言之,我想获取放置它的foo.jar"文件的路径.

Assuming my desktop application 'foo.jar' file is placed in d:\ in an installation of Windows. There is also a test.txt file in the same directory which I want to read when 'foo.jar' application is running. How can fetch that particular path in my 'foo.jar' application? In short I want to fetch the path of my 'foo.jar' file where it is placed.

推荐答案

请注意,实际代码确实取决于您的包中的实际类位置,但通常看起来像:

Note, that actual code does depend on actual class location within your package, but in general it could look like:

URL root = package.Main.class.getProtectionDomain().getCodeSource().getLocation();
String path = (new File(root.toURI())).getParentFile().getPath();
...
// handle file.txt in path

这篇关于从放置 jar 文件的特定目录中获取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆