NoSuchFileException while running jar file

Viewed 51

When we convert code to jar file we get this error. the code works with 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

1 Answers

Using Paths.get("..\\termproject\\word_database.txt") assumes that there is a directory "..\termproject\word_database.txt" starting at the current working directory. 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. Then this will be accessible via getClass().getResourceAsStream("/word_database.txt"). Now you can read the text from the file with a BufferedReader like so:

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