【发布时间】:2016-02-27 07:15:35
【问题描述】:
我的目标是使用带有可执行 jar 文件的 Apache CLI 来读取文本文件,执行字符串操作,然后写入 CSV。您可以像这样在终端中执行该工具:
$ java -jar my-tool-with-dependencies.jar -i input.txt -o output.csv
我已经为此功能编写了测试并且这些测试通过了。测试输入文本文件位于src/test/resources/。以下测试通过:
@Test
public void testWordockerWriteCsvFileContents() {
// Make sure the csv file contains contents
Wordocker w = new Wordocker();
String intext = "/textformat/example_format.txt";
String outcsv = "/tmp/foo.csv";
w.writeCsvFile(intext, outcsv);
try {
Reader in = new FileReader(outcsv);
Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
for (CSVRecord record : records) {
assertTrue(record.toString().length() > 0);
}
} catch(FileNotFoundException e){
assertTrue(false);
} catch(IOException e) {
assertTrue(false);
}
File file = new File(outcsv);
if (file.exists()) {
file.delete();
}
}
我们使用 mvn clean compile assembly:single 编译我的 jar 文件,然后引发以下 FileNotFoundException:
// Get file from resources folder
URL resourceURL = ParseDoc.class.getClassLoader().getResource(fileName);
if (resourceURL == null) {
throw new FileNotFoundException(fileName + " not found");
}
file = new File(resourceURL.getFile());
这让我相信ParseDoc.class.getClassLoader().getResource(fileName); 在哪里寻找文件存在问题。我知道已提出的相关问题。相关问题如下:
- Strange behavior of Class.getResource() and ClassLoader.getResource() in executable jar
- What is the difference between Class.getResource() and ClassLoader.getResource()?
- MyClass.class.getClassLoader().getResource(“”).getPath() throws NullPointerException
- this.getClass().getClassLoader().getResource(“…”) and NullPointerException
- getResourceAsStream returns null
这些问题似乎都没有询问如何将可执行 jar 与 Apache CLI 一起使用。我认为基本问题是URL resourceURL = ParseDoc.class.getClassLoader().getResource(fileName); 找不到我的命令行参数给出的文件路径。
请告诉我你的想法。感谢您的宝贵时间。
【问题讨论】:
-
您为什么不在测试中使用 FileReader? GetResource 仅查找打包在 jar 文件中的文件,这是您要执行的操作吗?
-
绝对不是,听起来 FileReader 是要做的事情。
标签: java maven jar apache-commons-cli