我正在尝试创建一个用于生成随机单词的类。到目前为止,我的选择是Scanner
或BufferReader
我猜。
这是我认为最有效的代码,但是当我运行时,我得到null
。
公共归还randomWord
获取者是否会授予对主要类中单词的访问权限?
private static final String filepath = "/assets/words.txt";
public String randomWord;
public Random rand;
private ArrayList<String> words = new ArrayList<String>();
public void WordGenerator() {
rand = new Random();
String line;
try {
InputStream WordsFile = getClass().getResourceAsStream(filepath);
BufferedReader br = new BufferedReader(new InputStreamReader(WordsFile));
if(!br.ready()){
System.out.println("No File");
}
else while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
}
catch (IOException e) {
System.out.println("Something is wrong");
}
int size = words.size();
Random rn = new Random();
int randWord = rn.nextInt(size);
randomWord = words.get(randWord);
System.out.println(randomWord);
}
}
答案 0 :(得分:1)
我认为您真正需要阅读的文件是删除InputStream
行,只需将BufferedReader
替换为此行:
BufferedReader br = new BufferedReader(new FileReader(filepath));
所以你的代码看起来像这样:
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
public class WordGeneratorClass
{
private static final String filepath="../assets/words.txt";
public String randomWord;
public Random rand;
private ArrayList<String> words=new ArrayList<String>();
public void WordGenerator()
{
rand=new Random();
String line;
try
{
BufferedReader br = new BufferedReader(new FileReader(filepath));
if(!br.ready())
{
System.out.println("No File");
}
else while((line=br.readLine())!=null)
{
words.add(line);
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
int size=words.size();
Random rn=new Random();
int randWord=rn.nextInt(size);
randomWord=words.get(randWord);
System.out.println(randomWord);
}
public static void main(String args[])
{
WordGeneratorClass gen = new WordGeneratorClass();
gen.WordGenerator();
}
}
确保您的assets/words.txt
存在。
修改强>
似乎问题也与您words.txt
的路径有关。上面的代码假定assets/words/words.txt
与源代码在同一目录中。有关详细信息,请查看here。