Java将单词读入字符串数组列表
我想通过缓冲读取器将文件game-words.txt读入字符串数组列表。我已经将缓冲读取器设置为从game-words.txt读取,现在我只需要弄清楚如何将其存储在ArrayList中。感谢您的帮助和耐心! 以下是我到目前为止的情况:Java将单词读入字符串数组列表,java,arraylist,Java,Arraylist,我想通过缓冲读取器将文件game-words.txt读入字符串数组列表。我已经将缓冲读取器设置为从game-words.txt读取,现在我只需要弄清楚如何将其存储在ArrayList中。感谢您的帮助和耐心! 以下是我到目前为止的情况: import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOExecption; class Dictionary{ S
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();
}
}
将字符串读入数组: 自动:
List<String> strings = Files.readAllLines(Path);
可以,您可以使用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();
}
}
这也会有帮助:
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变量作为参数 您在ArrayList;上查找过Java API吗?返回一个列表你能告诉我如何在我的代码中实现它吗?很抱歉,Java新手!是的,我仍然感到困惑:/@javaPhobicHow文件中存储的单词是什么?每条线上都有吗?它们是用逗号分隔的吗?
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();
}
}
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();
}
}