Java:将文本文件读入数组

时间:2015-03-13 16:09:51

标签: java arrays text

我有一个由两列组成的txt文件,如下所示:

Name1     _     Opt1
Name2     _     Opt2
Name3     _     Opt3

在每一行中都有一个名称,一个制表符分隔符,一个_然后是另一个名称;有很多行(大约150000),我甚至不确定哪一个是最好的构造函数,我考虑的是一个二维数组,但它可能也是其他东西,如果它'一个更好的选择。对我来说,重要的是我可以使用像这样的[x] [y]来访问元素。 我已经完成了这个,但我只知道如何计算行数或如何将每行放在数组的不同位置。 这是代码:

int countLine = 0;
    BufferedReader reader = new BufferedReader(new FileReader(filename));
    while (true) {
        String line = reader.readLine();
        if (line == null) {
            reader.close();
            break;
        } else {
            countLine++;
        }
    }

4 个答案:

答案 0 :(得分:2)

由于您不知道提前行数,我会使用ArrayList而不是数组。可以使用正则表达式轻松地将行拆分为字符串值。

Pattern pattern = Pattern.compile("(.*)\t_\t(.*)");
List<String[]> list = new ArrayList<>();
int countLine = 0;

BufferedReader reader = new BufferedReader(new FileReader(filename));
while (true) {
    String line = reader.readLine();
    if (line == null) {
        reader.close();
        break;
    } else {
        Matcher matcher = pattern.matcher(line);
        if (matcher.matches()) {
            list.add(new String[] { matcher.group(1), matcher.group(2) });
        }
        countLine++;
    }

答案 1 :(得分:0)

您应该做的第一件事是编写一个表示文件中条目的类。它可能非常复杂,但也可能是一个非常简单的设计。

class Record {

    final String name;
    final String option;

    Record(final String name, final String option) {
        this.name = name;
        this.option = option;
    }
}

使用这个类比搞乱字符串数组要好得多。

要做的第二件事是使用比数组结构更抽象的数据结构来放入记录。这将使您免于必须提前知道元素的数量。我建议您使用ArrayList。然后,您可以一次读入一条记录并将其添加到您的收藏中。

List<Record> records = new ArrayList<Record>();
records.add(new Record("NameX", "OptionX"));
System.out.printf("There are %d records in the list.%n", records.size());

当然,上面例子中的第二行应该在读取文件行的​​循环中反复进行。

答案 2 :(得分:0)

您可以将数据保存在

的HashMap&GT;

第一个String(键)是你的名字 第二个String(键)是您的选择,他的值(reault)是对象结果。

您可以将其用作:

result = youHashMap.get(name).get(opt);

答案 3 :(得分:0)

使用ArrayList而不是数组,因为大小未知。使用Scanner读取文件,并检查文件中是否存在下一行hasNextLine()方法,

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

class Test {
    static Scanner userInput = new Scanner(System.in);

    public static void main(String args[]) throws FileNotFoundException {

        int countline = 0;
        Scanner inp=new Scanner(new File("/home/nasir/Desktop/abc.txt"));
        ArrayList<String> list=new ArrayList<String>();

        while(inp.hasNextLine()){
            list.add(inp.nextLine());// adding a row in ArrayList
            countline++;// counting every line/row
        }

        System.out.println(countline+" "+list.get(2));
    }// Main
}// Class