我想通过缓冲读取器将文件(game-words.txt)读入字符串的ArrayList中。我已经设置了缓冲读取器来从game-words.txt读入,现在我只需要弄清楚如何将它存储在ArrayList中。在此先感谢您的帮助和耐心! 以下是我到目前为止的情况:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOExecption;
class Dictionary{
String [] words; // or you can use an ArrayList
int numwords;
// constructor: read words from a file
public Dictionary(String filename){ }
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("game-words.txt"));
while ((line = br.readLine()) != null){
System.out.println(line);
}
} catch (IOExecption e) {
e.printStackTrace();
}
}
答案 0 :(得分:2)
将字符串读入数组:
自动:
List<String> strings = Files.readAllLines(Path);
手册:
List<String> strings = new ArrayList<>();
while ((line = br.readLine()) != null){
strings.add(line);
}
将行拆分为单词(如果一行包含多个单词):
for(String s : strings) {
String[] words = s.split(" "); //if words in line are separated by space
}
答案 1 :(得分:1)
是的,您可以使用arrayList存储要添加的单词。 您只需使用以下命令对文件进行反序列化即可。
ArrayList<String> pList = new ArrayList<String>();
public void deserializeFile(){
try{
BufferedReader br = new BufferedReader(new FileReader("file_name.txt"));
String line = null;
while ((line = br.readLine()) != null) {
// assuming your file has words separated by space
String ar[] = line.split(" ");
Collections.addAll(pList, ar);
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
答案 2 :(得分:1)
这也可能有用:
class Dictionary{
ArrayList<String> words = new ArrayList<String>(); // or you can use an ArrayList
int numwords;String filename;
// constructor: read words from a file
public Dictionary(String filename){
this.filename =filename;
}
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("game-words.txt"));
while ((line = br.readLine()) != null){
words.add(line.trim());
}
} catch (IOExecption e) {
e.printStackTrace();
}
}
我使用了trim,它会删除单词中的前导和尾随空格(如果有的话)。如果你想将文件名作为参数传递,请使用Filereader中的filename变量作为参数。