简体   繁体   English

运行 jar 文件时出现 NoSuchFileException

[英]NoSuchFileException while running jar file

When we convert code to jar file we get this error.当我们将代码转换为 jar 文件时,我们会收到此错误。 the code works with IDE该代码适用于 IDE

public String getwordleString() {

        Path path = Paths.get("..\\termproject\\word_database.txt");
        List<String> wordList = new ArrayList<>();
        try {
            wordList = Files.readAllLines(path);
        } catch (IOException e) {

            e.printStackTrace();
        }

        Random random = new Random();
        int position = random.nextInt(wordList.size());
        return wordList.get(position).trim().toUpperCase();
    }

Error part is : https://ibb.co/z6vZLW5错误部分是: https ://ibb.co/z6vZLW5

Using Paths.get("..\\termproject\\word_database.txt") assumes that there is a directory "..\termproject\word_database.txt" starting at the current working directory.使用Paths.get("..\\termproject\\word_database.txt")假定从当前工作目录开始有一个目录 "..\termproject\word_database.txt"。 If the file does not exist, you will get an error.如果该文件不存在,您将收到错误消息。
If you want to wrap the directory with the JAR, you can set you "termproject" file as a src or class file.如果要使用 JAR 包装目录,可以将“termproject”文件设置为 src 或类文件。 Then this will be accessible via getClass().getResourceAsStream("/word_database.txt") .然后这将可以通过getClass().getResourceAsStream("/word_database.txt") Now you can read the text from the file with a BufferedReader like so:现在您可以使用 BufferedReader 从文件中读取文本,如下所示:

BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/word_database.txt")));
String data = reader.lines().collect(Collectors.joining("\n"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM