Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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++;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...