Abe
Bobby
Joseph
yyvoynne
Kathryn
^^我正在读取的文件。我如何一次读取一个单词,将这个单词赋值给一个变量,对它做一些操作,然后从文件中读取另一个名称?我只是在纠结如何将我读入的单词赋值给一个变量。谢谢你的宝贵时间。
while(names.hasNext())
{
//Stuff
}
我想你是想从文件中逐行读取。
你可以试试这个:这是从文件中读取的一种常用方法。
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
String word;
while ((line = br.readLine()) != null) {
word = line;
//do stuff with word
}
br.close();
while(names.hasNext())
{
String name = names.next(); // Assuming Scanner is used to read file
}
也许你想要这样:
while(names.hasNext()){
String name = names.next();
... do stuff...
}
Path path = Paths.get("names-in-cwd.txt"); /* Relative or absolute path here. */
Charset encoding = StandardCharsets.UTF_8; /* Or whatever it is really. */
for (String name : Files.readAllLines(path, encoding)) {
/* Do stuff with value in "name" variable ... */
}
您可以使用Scanner
并使用useDelimiter(String regex)
方法来完成此操作:
确保添加了这些导入:
import java.util.ArrayList;
import java.util.Scanner;
然后你可以这样做,使用ArrayList来保存名称。
try {
Scanner file = new Scanner(new File("yourFileNameAndPath.txt"));
file.useDelimiter("\s+"); // split names by any whitespace
// list is the ArrayList to hold all of the names
ArrayList<String> list = new ArrayList<String>();
while (file.hasNext()) {
list.add(file.next());
}
// print it out to test
// new element (name) after every ###
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i) + "###");
}
print(list.size()); // print number of names found
} catch (Exception e) {
System.out.println("Error");
}
对于您的文件,这是输出:
Abe###
Bobby###
Joseph###
yyvoynne###
Kathryn###
5