Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从src文件夹将文件加载到ArrayList_Java_File_Arraylist - Fatal编程技术网

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

Java 如何从src文件夹将文件加载到ArrayList,java,file,arraylist,Java,File,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 SETT

我一直在尝试很多事情,我只是准备寻求一些帮助。如果这是不够的信息,请让我知道。我曾尝试过扫描器、缓冲阅读器等搜索帖子,但没有成功

我的文件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(); } }
使用顶级ContextClassLoader获取文件

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

请改用此代码行:

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

请注意路径和文件之间的差异。以大写字母开始Java类名,这是一种惯例。

线程main Java.lang.NullPointerException在secretWord.createArraysecretWord.Java:27在secretWord.secretWord.Java:21在frame.theFrame.Java:33在game.maintheGame.Java:6当我使用Scanner Scanner=new Scanner new Filewords.txt时;我得到文件找不到异常。