Apache CLI、可执行 jar、classLoader().getResource()

Apache CLI, Executable jar, classLoader().getResource()

我的目标是使用带有可执行 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); 查找文件的位置存在问题。我知道已被问到的相关问题。相关问题如下:

None 这些问题似乎是在询问如何在 Apache CLI 中使用可执行 jar。我认为基本问题是 URL resourceURL = ParseDoc.class.getClassLoader().getResource(fileName); 无法找到我的命令行参数给出的文件路径。

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

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

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

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