java上传文件相对路径,Java:数据文件的相对路径

I have developed a GUI application in NetBeans (v. 7.2.1) on Mac (OS version 10.6.8). This application requires an XML file (containing data used by the program), which I would like to place in a subdirectory data.

The trouble is that if I want to run my application from within NetBeans, this data directory has to be placed inside the main project directory; however, if I want to simply run the .jar file (using a doubleclick), located in the dist subdir of the main dir, I have to move the data folder into dist - and then the program will no longer run from within NetBeans.

This is how the data file path is specified within the program:

public String vocabPath = "data" + File.separator + "wordlist.xml";

public File vocabFile = new File(vocabPath);

In itself at first this did not seem problematic, as, for redistribution of the application, I thought I could simply move the data directory into dist, and distribute that (which worked fine on OS X and Windows 7); however, on Ubuntu I got an error message saying the data file was not found.

I am new to Java, so perhaps this is a daft question, but anyway: how can I get my application to always access the data file located in MAIN_DIR/dist/data? Or if the root of the problem lies somewhere else, then please let me know.

Thanks a lot in advance!

EDIT

I have posted a follow-up question, as I think I have narrowed down the problem to some unexpected behaviour which only occurs under Ubuntu.

EDIT 2

An answer to my follow-up question (see first edit) has solved my problem (just as a note to those who've found this post while trying to solve a problem similar to mine).

解决方案

If the file wordlist.xml is not modifiable by user, you could include it as part of jar and use getResourceAsStream() to load it. Some additional details are here at getResourceAsStream() vs FileInputStream

if the data is expected to be modified , you may keep it at some known location. Users home directory is available via user.home property. (and is probably a good area)

Having a file relative to 'installation' (MAIN_DIR) is more difficult if it is a pure java program started by java command. You may create an executable and the use some operating system api (readlink ("/proc/self/exe", ..) on Linux) to resolve the installation location.

Packaging java program with native executable could be done by software like exe4j.

(Launch4J is an opensource solution with similar features, could be useful here)

(For the sake of completion and future reference). You could also try to create a small batch script on windows and shell script on Linux. It is possible to detect the installation area from both.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值