0

我在扫描给定文件中的某些单词并将它们分配给变量时遇到问题,到目前为止,我选择使用 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
...
4

3 回答 3

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 ",">

输出:

VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
于 2013-09-17T04:07:40.457 回答
0

换句话说,您希望读取一行的前两个单词(第一个逗号之前的所有内容)并将其存储在一个变量中以进一步处理。

为此,您当前的代码看起来不错,但是,当您获取该行的数据时,请substring结合使用该函数indexOf来获取逗号之前的字符串的第一部分。之后,您可以对其进行任何处理。

在您当前的代码中, ary[0] 应该给您前 2 个单词。

于 2013-09-17T03:47:50.330 回答
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]);
        }

    }
于 2013-09-17T08:09:41.060 回答