【问题标题】:Apache CLI, Executable jar, classLoader().getResource()Apache CLI、可执行 jar、classLoader().getResource()
【发布时间】: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); 在哪里寻找文件存在问题。我知道已提出的相关问题。相关问题如下:

这些问题似乎都没有询问如何将可执行 jar 与 Apache CLI 一起使用。我认为基本问题是URL resourceURL = ParseDoc.class.getClassLoader().getResource(fileName); 找不到我的命令行参数给出的文件路径。

请告诉我你的想法。感谢您的宝贵时间。

【问题讨论】:

  • 您为什么不在测试中使用 FileReader? GetResource 仅查找打包在 jar 文件中的文件,这是您要执行的操作吗?
  • 绝对不是,听起来 FileReader 是要做的事情。

标签: java maven jar apache-commons-cli


【解决方案1】:

在通过 cmets 讨论后,我也将其作为答案发布:

Classloader.getResource() 仅获取打包为 Jar 文件的一部分或位于类路径文件夹中的文件。

要读取普通文件,您可以使用类似于第一个示例的内容,即 FileReaderFileInputStream 或简单地传递 java.io.File,具体取决于您尝试使用的库支持的内容。

【讨论】:

    猜你喜欢
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 2020-10-15
    • 1970-01-01
    • 2014-10-02
    相关资源
    最近更新 更多