問題描述
我將一些對象存儲在文件中,并且在 Netbeans 控制臺中一切正常.但是當我通過命令行(java -jar myapp.jar)運行 JAR 時,我得到了這個:
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:
我應該將文件放在哪里才能通過命令行運行應用程序?
Where should i place the files in order to be able run the app through the command line?
推薦答案
答案將取決于您是否要寫入文件...
The answer will depend on if you want to write to the files or not...
確保文件相對于 Jar 文件放置并使用相對路徑.這樣做的問題是,如果執行上下文與存儲 jar 和文件的目錄不同,您將無法再次找到它們...
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...
這也將取決于您的構建過程,以確保將所有需要的文件復制到 Jar 的構建位置
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}
并將文件放在這里,然后您可以使用文件的絕對路徑
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
這可能會成為安裝問題,因為您需要確保在安裝應用程序時將所有所需文件復制到所需位置.
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.
如果文件是在運行時自動生成的,那么您只需要確保目錄存在,如果不存在則創建它們
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
將文件存儲在 Jar 上下文(也稱為嵌入式資源)中,執行此操作的方式取決于您的 IDE 和構建過程,例如,在 Netbeans 中,您可以將文件復制到 src
目錄,它們將自動包含在生成的 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.
這將使資源只讀.
這篇關于我應該把我的文件放在哪里以便在我運行 jar 時能夠訪問它們?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!