我在扫描给定文件中的某些单词并将它们分配给变量时遇到问题,到目前为止,我选择使用 Scanner 而不是 BufferedReader,因为它更熟悉。我得到了一个文本文件,在这个特定部分中,我试图读取每行的前两个单词(可能是无限行),并可能将它们添加到一个数组中。这就是我所拥有的:
File file = new File("example.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] ary = line.split(",");
我知道距离很远,但是我是编码新手,无法越过这堵墙......
示例输入是...
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
...
以及建议的输出
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
...
最佳答案
你可以尝试这样的事情
File file = new File("D:\\test.txt");
Scanner sc = new Scanner(file);
List<String> list =new ArrayList<>();
int i=0;
while (sc.hasNextLine()) {
list.add(sc.nextLine().split(",",2)[0]);
i++;
}
char point='A';
for(String str:list){
System.out.println("Variable"+point+" = "+str);
point++;
}
我的输入:
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
输出:
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
关于java - 从文本文件中扫描、分割和赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18840970/