user2576739
user2576739

Reputation: 3

How to load file to ArrayList from src folder

I have been trying a lot of things and I just ready to ask for some help. if this is not enough info please let me know. I have tried Scanner, BufferReader, etc from searching posts with no luck.

I have the file words.txt right in the src directory.

    import java.io.File;
    import java.util.ArrayList;
    import java.util.Random;
    import java.util.Scanner;


    /*
     * CLASS THAT HANDLES GETTING AND SETTING THE SECRET WORD RANDOMLY
     */

    public class secretWord {
        private ArrayList theWordList;
        private Scanner scanner; //Used to read the file into the array
        private Random random; //Generates a random number index for choosing a random array element
        private int randomIndex; //Holds the random index generated
        ArrayList theSecretWord= new ArrayList(); //The secret word converted to char[] for use in the program
        String tempSecretWord; //Secret word selected as string

        //Constructor: runs methods to create arraylist of words then select a random element for thesecretword
        public secretWord(){
            createArray();
            getSecretWord();
        }
        //Creates an ArrayList of words from file
        private void createArray(){
            theWordList= new ArrayList();
            String file= getClass().getResource("words.txt").getPath();
            File f= new File(file);
            try{
            Scanner scanner= new Scanner(f);

            while(scanner.hasNext()){
                theWordList.add(scanner.nextLine());
            }

            }catch(Exception e){
                e.printStackTrace();
            }finally{
                scanner.close();
            }
        }
        //Selects a random number from the ArrayList to use as the secret word
        private void getSecretWord(){
            random= new Random();
            randomIndex= random.nextInt(theWordList.size());
            theSecretWord.add(theWordList.get(randomIndex).toUpperCase());
        }
        //Removes the secretWord and gets a new one for another play
        void refreshWord(){
            theSecretWord.clear();
            getSecretWord();
        }
    }

Upvotes: 0

Views: 707

Answers (2)

winne2
winne2

Reputation: 2250

Use this code line instead:

String file= getClass().getResource("words.txt").getFile();

Note the difference between path and file. And start your Java class names with capital letters, this is a convention.

Upvotes: 0

bsd
bsd

Reputation: 2717

Use the top level ContextClassLoader to get the file.

     InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("words.txt");
     Scanner in = new Scanner(inStream);

Upvotes: 1

Related Questions