2013-07-12 139 views
0

我一直在嘗試很多事情,而我只是準備請求一些幫助。如果這是不夠的信息,請讓我知道。我試過Scanner,BufferReader等搜索帖子沒有運氣。如何從src文件夾中將文件加載到ArrayList

我的文件words.txt就在src目錄中。

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

異常在secretWord.createArray(secretWord.java:27)線程 「主」 顯示java.lang.NullPointerException \t \t 在secretWord中。 (secretWord.java:21) \t at theFrame。 (theFrame.java:33) \t at theGame.main(theGame.java:6) – user2576739

+0

當我使用Scanner scanner = new Scanner(new File(words.txt));我得到文件未找到異常。 – user2576739

回答

0

使用頂級ContextClassLoader來獲取文件。

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

這解決了這個問題!謝謝你的幫助! – user2576739

0

使用此代碼行:

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

注意路徑和文件之間的差異。並且用大寫字母開始你的Java類名,這是一個慣例。

相關問題