Nit*_*eti 4 java deployment absolute-path
这个主题有很多混乱.有人问过几个问题.事情似乎还不清楚.ClassLoader,绝对文件路径等
假设我有一个项目目录结构,
MyProject--
--dist
--lib
--src
--test
我在"lib/txt"目录中有一个资源说"txtfile.txt".我想以独立于系统的方式访问它.我需要项目的绝对路径.所以我可以将路径编码为abspath +"/ lib/Dictionary/txtfile.txt"
假设我这样做
java.io.File file = new java.io.File(""); //Dummy file
String abspath=file.getAbsolutePath();
Run Code Online (Sandbox Code Playgroud)
我得到当前的工作目录,不一定是项目根目录.
假设我从'dist'文件夹执行最后的'prj.jar',该文件夹还包含"lib/txt/txtfile.txt"目录结构和资源,它也应该在这里工作.我应该是dist文件夹的绝对路径.
希望问题很清楚.
您应该使用类加载器来使用getResource()或getResourceAsStream()来实现此类操作.特别是,这些方法使用ClassLoader来确定项目中资源的搜索上下文.
指定类似getClass().getResource("lib/txtfile.txt")的内容以便获取文本文件.
澄清:而不是考虑如何获取资源的路径,而应该考虑获取资源 - 在这种情况下是某个目录中的文件(可能在JAR中).在这种情况下,没有必要知道一些绝对路径,只有一些URL来获取文件,ClassLoader将为您返回此URL.如果要打开文件流,可以直接执行此操作,而无需使用URL来处理getResourceAsStream.
The resources you're trying to access through the ClassLoader need to be on the Class-Path (configured in the Manifest of your JAR file). This is critical! The ClassLoader uses the Class-Path to find the resources, so if you don't provide enough context in the Class-Path it won't be able to find anything. If you add . the ClassLoader should resolve anything inside or outside of the JAR depending on how you refer to the resource, though you can certainly be more specific.
Referring to the resource prefixed with a . will cause the ClassLoader to also look for files outside of the JAR, while not prefixing the resource path with a period will direct the ClassLoader to look only inside the JAR file.
这意味着,如果你有一些文件中的目录中JAR lib与名称foo.txt,你想要得到的资源,那么你会运行getResource("lib/foo.txt");
如果相同的资源在JAR之外,那么你就会运行 getResource("./lib/foo.txt");
| 归档时间: |
|
| 查看次数: |
45499 次 |
| 最近记录: |