Abe
Bobby
Joseph
yyvoynne
Kathryn
^^我正在阅读的文件。我如何一次只读一个单词,将一个单词分配给变量,对其进行处理,然后从文件中读取另一个名称?我真的只是被困在如何将我读入的单词分配给变量。谢谢你的时间。
while(names.hasNext())
{
//Stuff
}
答案 0 :(得分:2)
我认为你正在寻找从文件中逐行阅读。
你可以试试这个:它是从文件中读取的常用方法。
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
String word;
while ((line = br.readLine()) != null) {
word = line;
//do stuff with word
}
br.close();
答案 1 :(得分:0)
while(names.hasNext())
{
String name = names.next(); // Assuming Scanner is used to read file
}
答案 2 :(得分:0)
也许你想要这个:
while(names.hasNext()){
String name = names.next();
... do stuff...
}
答案 3 :(得分:0)
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 ... */
}
答案 4 :(得分:0)
您可以使用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