如何从src文件夹中将文件加载到ArrayList

时间:2013-07-12 16:07:50

标签: java file arraylist

我一直在尝试很多事情,我只是准备寻求帮助。如果这还不够,请告诉我。我已经尝试ScannerBufferReader等来搜索没有运气的帖子。

我在src目录中有words.txt文件。

    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();
        }
    }

2 个答案:

答案 0 :(得分:0)

使用顶级ContextClassLoader获取文件。

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

答案 1 :(得分:0)

请改用此代码行:

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

注意路径和文件之间的区别。并用大写字母开始你的Java类名,这是一个惯例。