Search code examples
javafilewords

Java - how to put all words from a textfile with a specific length in a List


So I have a wordlist called wordlist.txt and I want to put all words that have a specific length, let's say 5, and put them in a list.

First I tried to just get all the words into a list, for testing purposes but I got an error "Cannot resolve symbol 'exists'" when I tried Files.exists, it works in the Main function but not in a class for some reason. Image Error

    ArrayList<String> list = new ArrayList<>();
private Path myFile = Paths.get("Resources/wordlist.txt");
if (Files.exists(myFile)){
    try (Scanner fileScanner = new Scanner(myFile)){
        while (fileScanner.hasNext()) {
            list.add(fileScanner.nextLine());
        }
    } catch (IOException ioe){
        System.out.println("The file doesn't exists!");
    }
}

Solution

  • Firstly, remove the private modifier - it is not allowed to be inside a method. That should resolve your syntax error.

    Secondly, I suggest you follow the folder structure as a brief example states below:

    src/main/java
     - Main.java  
    src/main/resources
     - wordlist.txt
    

    You are ready you can access the file using the ClassLoader. If Files.exists(myFile) returns true, the IOException won't be thrown. Try the following code:

    ArrayList<String> list = new ArrayList<>();
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    File file = new File(classLoader.getResource("wordlist.txt").getFile());
    try (Scanner fileScanner = new Scanner(file)) {
        while (fileScanner.hasNext()) {
            list.add(fileScanner.nextLine());
        }
    } catch (IOException ioe) {
        System.out.println("The file doesn't exists!");
    }
    

    Finally, the label of the question doesn't match with what do you ask. I am not sure whether I understand "put all words" correctly. Anyway, let's suggest the text file contains one word on each line, thus check it's length and decide to add to the list or not.

    while (fileScanner.hasNext()) {
        String line = fileScanner.nextLine();
        if (line.length() == 5) { // specific length, use a constant is better          
            list.add(line);
        }
    }