Java:导出到JAR后,Pathnames不工作 [英] Java: Pathnames not working once I export to JAR
问题描述
String file =src / Files / .. 。;
loadFile(file); //纯粹例如
现在项目采用JAR的形式,似乎存在并加载这些文件失败。我很确定我引用的文件被包装在JAR中。当导出到JAR时,目录是否以任何特定的方式发生变化?任何有关如何使这项工作的其他想法?
您需要将它们视为类路径资源,而不是本地磁盘文件系统路径。当您将文件打包在JAR中时,这不会起作用,也不希望依赖于工作目录。 JAR中的文件已经是类路径的一部分。
假设你有一个 foo.txt
包 com.example
,那么你可以得到一个 InputStream
,如下
InputStream input = getClass()。getResourceAsStream(/ com / example / foo.txt);
// ...
或当您在 static
context
InputStream input = SomeClass.class.getResourceAsStream(/ com / example / foo。文本);
// ...
或者当您要扫描全局类路径时
InputStream input = Thread.currentThread()。getContextClassLoader()。getResourceAsStream(/ com / example / foo.txt);
// ...
另请参见:
- 如何从Java项目的相对路径读取文件? java.io.File找不到指定的路径
- getResourceAsStream ()vs FileInputStream
I have exported a project to a runnable JAR in eclipse. There are a few places in my code where I've done the following.
String file = "src/Files/...";
loadFile(file); // purely for example
Now that the project is in the form of a JAR, those directories don't seem to exist and loading those files fails. I'm pretty sure that the files I'm referencing are packed in the JAR. Do the directories change in any particular way when exported to JAR? Any other ideas on how to make this work?
You need to treat them as a classpath resource, not as a local disk file system path. This isn't going to work when you package the files in a JAR and you also don't want to be dependent on the working directory. Files inside a JAR are part of the classpath already.
Assuming that you've a foo.txt
file in package com.example
, then you can get an InputStream
of it as follows
InputStream input = getClass().getResourceAsStream("/com/example/foo.txt");
// ...
Or when you're inside static
context
InputStream input = SomeClass.class.getResourceAsStream("/com/example/foo.txt");
// ...
Or when you want to scan the global classpath
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("/com/example/foo.txt");
// ...
See also:
- How to read file from relative path in Java project? java.io.File cannot find the path specified
- getResourceAsStream() vs FileInputStream
这篇关于Java:导出到JAR后,Pathnames不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!