Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

Java: Read a text file into an array

I've a txt file composed by two columns like this:

Name1     _     Opt1
Name2     _     Opt2
Name3     _     Opt3

In each row there's a name, a tab delimiter, a _ and then another name; there are really many rows (about 150000) and i'm not even sure which one is the best constructor to use, i'm thinking about a two dimensional array but it could be also something else if it's a better choice. For me it's important that i can access to the elements with something like this a[x][y]. I've done this but i just know how to count the number of the lines or how to put each lines in a different position of an array. Here's the code:

int countLine = 0;
    BufferedReader reader = new BufferedReader(new FileReader(filename));
    while (true) {
        String line = reader.readLine();
        if (line == null) {
            reader.close();
            break;
        } else {
            countLine++;
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you don't know the number of lines ahead of time, I would use an ArrayList instead of an array. The splitting of lines into String values can easily be done with a regular expression.

Pattern pattern = Pattern.compile("(.*)	_	(.*)");
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++;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...