我无法扫描给定文件中的某些单词并将它们分配给变量,到目前为止我选择使用Scanner over 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
...
答案 0 :(得分:2)
您可以尝试这样的事情
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 ",">
Out put:
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
答案 1 :(得分:0)
要改写一下,您希望阅读一行中的前两个单词(第一个逗号之前的所有内容)并将其存储在变量中以进一步处理。
为此,您当前的代码看起来很好,但是,当您获取行的数据时,将substring
函数与indexOf
结合使用,只需获取逗号前的字符串的第一部分。之后,您可以对其进行任何处理。
在你当前的代码中,ary [0]应该给你前两个单词。
答案 2 :(得分:0)
public static void main(String[] args)
{
File file = new File("example.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
List l = new ArrayList();
while ((line = br.readLine()) != null) {
System.out.println(line);
line = line.trim(); // remove unwanted characters at the end of line
String[] arr = line.split(",");
String[] ary = arr[0].split(" ");
String firstTwoWords[] = new String[2];
firstTwoWords[0] = ary[0];
firstTwoWords[1] = ary[1];
l.add(firstTwoWords);
}
Iterator it = l.iterator();
while (it.hasNext()) {
String firstTwoWords[] = (String[]) it.next();
System.out.println(firstTwoWords[0] + " " + firstTwoWords[1]);
}
}