問(wèn)題描述
我將一些對(duì)象存儲(chǔ)在文件中,并且在 Netbeans 控制臺(tái)中一切正常.但是當(dāng)我通過(guò)命令行(java -jar myapp.jar)運(yùn)行 JAR 時(shí),我得到了這個(gè):
I store some objects in files and everything works fine in Netbeans console. But when i run the JAR through the command line (java -jar myapp.jar) i get this:
我應(yīng)該將文件放在哪里才能通過(guò)命令行運(yùn)行應(yīng)用程序?
Where should i place the files in order to be able run the app through the command line?
推薦答案
答案將取決于您是否要寫(xiě)入文件...
The answer will depend on if you want to write to the files or not...
確保文件相對(duì)于 Jar 文件放置并使用相對(duì)路徑.這樣做的問(wèn)題是,如果執(zhí)行上下文與存儲(chǔ) jar 和文件的目錄不同,您將無(wú)法再次找到它們...
Ensure that the files are placed relative to the Jar file and use a relative path. The problem with this is if the execution context is not the same directory as where the jar and files are stored, you won't be able to find them again...
這也將取決于您的構(gòu)建過(guò)程,以確保將所有需要的文件復(fù)制到 Jar 的構(gòu)建位置
This will also be dependent on your build process to make sure that any required files are placed copied to the build location of the Jar
將文件放在眾所周知的位置,例如,在 Windows 上您可以使用 {user.home}/AppData/Local/{application name}
或在 Mac 上您可以使用 {user.home}/Library/Application Support/{application name}
并將文件放在這里,然后您可以使用文件的絕對(duì)路徑
Place the files within a well know location, for example, on Windows you could use {user.home}/AppData/Local/{application name}
or on Mac you could use {user.home}/Library/Application Support/{application name}
and place the files here, then you could use an absolute path to the files
這可能會(huì)成為安裝問(wèn)題,因?yàn)槟枰_保在安裝應(yīng)用程序時(shí)將所有所需文件復(fù)制到所需位置.
This likely becomes an installation issue, as you need to ensure that any required files are copied to the required location when the application is installed.
如果文件是在運(yùn)行時(shí)自動(dòng)生成的,那么您只需要確保目錄存在,如果不存在則創(chuàng)建它們
If the files are auto generated at runtime, then you just need to make sure the directories exists and make them if they don't
將文件存儲(chǔ)在 Jar 上下文(也稱(chēng)為嵌入式資源)中,執(zhí)行此操作的方式取決于您的 IDE 和構(gòu)建過(guò)程,例如,在 Netbeans 中,您可以將文件復(fù)制到 src
目錄,它們將自動(dòng)包含在生成的 Jar 文件中.我相信 Eclipse 可以以同樣的方式工作.但是,如果您使用 Maven,則需要將文件放入 resources
目錄中.
Store the files within the Jar context (AKA embedded resources), the means by which you do this will depend on your IDE and build process, for example, in Netbeans, you can copy files into the src
directory of your project and they will automatically be included in the resulting Jar file. I believe that Eclipse can work the same way. However, if you're using Maven, you will need to place the files into the resources
directory instead.
然后您可以使用 Class#getResource
或 Class#getResourceAsStream
取決于你的需要.
You would then access these resources using Class#getResource
or Class#getResourceAsStream
depending on your needs.
這將使資源只讀.
這篇關(guān)于我應(yīng)該把我的文件放在哪里以便在我運(yùn)行 jar 時(shí)能夠訪(fǎng)問(wèn)它們?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!