Question

[Solved] 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++;
        }
    }

Solution #1:

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++;
    }
Respondent: Thomas

Solution #2:

The first thing you should do is to write a class that represents an entry in your file. It could be quite sophisticated but a really simple design will probably also do.

class Record {

    final String name;
    final String option;

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

Using this class is much better than messing with arrays of strings.

The second thing to do is to use a more abstract data structure than an array structure to put your records into. This will free you from the burden of having to know the number of elements in advance. I recommend that you use an ArrayList for this. Then, you can read in one record at a time and add it to your collection.

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());

Of course, the second line in the above example should be done over and over again in your loop that reads the lines of the file.

Respondent: 5gon12eder

Solution #3:

Use ArrayList instead of array because the size is unknown. Use Scanner to read file, and to check existence of next line in file use hasNextLine() method,

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

Solution #4:

You can save the data on

HashMap>

The first String (key) is your name
The second String (key) is your opt and his value (reault) is the object result.

You can use it as:

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

Respondent: Roy Shmuli

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy