【问题标题】:Fat Jar throwing File not found exception when trying to access text file within the jar尝试访问 jar 中的文本文件时,Fat Jar throwing File not found 异常
【发布时间】:2017-02-09 17:22:42
【问题描述】:

我已经用 Tree 数据结构构建了一个 Spring Boot MVC 应用程序来代替实际的数据库。该程序从文本文件中读取并将单词存储在树中。最初我使用 CommandLineRunner 类来填充树,它可以工作......但是在创建一个胖 jar 并运行 jar 之后,我得到一个文件未找到异常。如何用 maven 构建一个包含 maven 文本文件的胖 jar?

该文件当前位于项目根目录中。

这是生成树的逻辑:

@Component
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GenerateTree implements CommandLineRunner {

@Autowired
TreeRepository trie = new TreeRepository();

@Autowired
FileReader fileReader = new FileReader();


@Override
public void run(String... args) throws Exception {

    for (String s : fileReader.readFile("wordList1.txt")){
        trie.add(s);
    }
}
}

这是读取文件的逻辑:

@Component
public class FileReader {

List<String> readFile(String filename){
    List<String> list = new ArrayList<>();
    try (Stream<String> stream = Files.lines(Paths.get(filename))) {
        list = stream
                .filter(line -> line.matches("[a-zA-Z]+"))
                .collect(Collectors.toList());
    } catch (IOException e) {
        e.printStackTrace();
    }

    return list;
}
}

【问题讨论】:

  • 您是如何尝试访问该文件的?你能分享所涉及的代码和抛出的异常吗?

标签: maven spring-mvc jar spring-boot


【解决方案1】:

您无法访问 jar 中的文件(请参阅 https://stackoverflow.com/a/8258308/4516887)。 将wordlist.txt 放入src/main/resources 目录并使用[ClassPathResource][1] 读取其内容:

ClassPathResource resource = new ClassPathResource("worldlist.txt");
try (InputStream in = resource.getInputStream();
     BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {

    String line;
    while((line = reader.readLine()) != null) {
        ...
    }
}

【讨论】:

    猜你喜欢
    • 2014-03-22
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多