[英]Store .txt File in Arraylist
这是我读取文件的完整代码:
public static void main(String[] args) {
List <String> words = new ArrayList <String>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("3LetterWords.txt"));
String word;
while ((word = br.readLine()) != null ){
words.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
String [] wordList = new String[words.size()];
words.toArray(wordList);
List<String> combinations = display(new ArrayList<>());
}
public static List<String> display(ArrayList<String> combinations) {
int counter = 1;
for (char c1 = 'a'; c1 <= 'z'; c1++) {
for (char c2 = 'a'; c2 <= 'z'; c2++) {
for (char c3 = 'a'; c3 <= 'z'; c3++) {
String combo = "" + c1 + c2 + c3;
combinations.add(combo);
System.out.println("" + counter++ + " " + c1 + c2 + c3);
}
}
}
return combinations;
}
当我运行程序时,我在输出中得到一个错误,我不确定如何读取或解释(在 NetBeans 中)。 我希望读取.txt
文件,然后将其存储到ArrayList
中:创建ArrayList
以保存文件中的所有信息。 使用ArrayList
,这样您就不必知道文件的大小。
BufferedReader
命令定位文件并打开它以供阅读。
while
循环逐行读取信息,直到它看到“null”或“end of file”字符。 然后它将每个条目添加到ArrayList
。
catch
部分确保您不会读到文件末尾。
第二个try
部分关闭文件。
最后一个功能是将ArrayList
转换为数组,以便您可以通过它进行搜索。
添加了完整代码:对于上下文:我需要使用 3 个字母单词的 .txt 文件来在两个数组列表之间使用排序/搜索方法。
错误:
java.io.FileNotFoundException: 3LetterWords.txt (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:216)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:111)
at java.base/java.io.FileReader.<init>(FileReader.java:60)
at wordleproj.WordleProj.main(WordleProj.java:17)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.io.BufferedReader.close()" because "br" is null
at wordleproj.WordleProj.main(WordleProj.java:26)
/Users/mac/Library/Caches/NetBeans/12.6/executor-snippets/run.xml:111: The following error occurred while executing this line:
/Users/mac/Library/Caches/NetBeans/12.6/executor-snippets/run.xml:68: Java returned: 1
您需要在项目中创建文件3LetterWords.txt
或添加文件路径。
// you don't have the path but only the filename so the file should be in your project.
br = new BufferedReader(new FileReader("3LetterWords.txt"));
或指定路径
br = new BufferedReader(new FileReader("C:\\Users\\Admin\\Downloads\\3LetterWords.txt"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.