简体   繁体   中英

How to read/write external data resource from within runnable JAR?

I'd like to run MyRunnableJar.jar from command line. It will need to read from file_[1-4].dat , do some processing and then write to file_5.dat . All of the aforementioned data files are near MyRunnableJar.jar in the file system. For example:

  • super_directory/
    • MyRunnableJar.jar
    • data_resources/
      • file_1.dat
      • file_2.dat
      • file_3.dat
      • nested_data_directory/
        • file_4.dat
        • file_5.dat

( MyRunnableJar.jar was created by Eclipse's Export feature.)

The reason I want to do things this way is because the application is too computationally expensive to run on my little laptop. Instead, I want to put it on a remote server (with all the big data files that it has to access) and run it there.

The problem is, I can't figure out how to show the runnable JAR where those data files are. The data files can certainly be moved around if need be. However, keeping them inside the JAR is not an option, because if I want to change even a bit of the application code, I'd have to re-transfer the entire JAR, which would be quite large if it includes the data files. Moreover, I would be unable to write to file_5.dat if it was actually in my JAR.

I am aware that there are many questions similar to this on Stack Exchange, but in each case the question is slightly different in some important way.


EDIT:

  • Please see Accepted Answer.
  • Also note that Andre's solution (explained in the comment) also worked, since in my case, the JAR and the data file will always be in the same position in the filesystem relative to one another.

What you really need to be able to do is figure out what directory your .jar file is in regardless of what the System.property("user.dir"); returns or where the MyRunnableJar.jar is executed from. You don't want to have to assume that you are currently in the same directory as MyRunnableJar.jar , if you aren't you can't calculate the relative directory because you don't know where you are relative to that .jar anymore.

The following code snippet will do this for you:

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

replace MyClass with your main class

Then you can use that to build the path to the directory you want to read from. The is all cake from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM