0

Goal: I'm trying to process a .txt file into a String[]. File must be read per line, spliced on "," and stored in array. Each element (6 elements per line) must have it's own index in the array and must individually be accessible.

File (partially):

210,20140101,    1,   60,   67,   -1
210,20140101,    2,   60,   65,    0
210,20140101,    3,   60,   58,    0
210,20140101,    4,   60,   56,    0
210,20140101,    5,   60,   49,    0
210,20140101,    6,   60,   53,    0
210,20140101,    7,   60,   55,    0
210,20140101,    8,   70,   59,    0

Code so far:

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    for (String line; (line = br.readLine()) != null;) {
        counter++;
        if (counter > 51) {
            line = br.readLine();
            line = line.trim();
            list = Arrays.asList(line.split("\\s*,\\s*"));
        }
    }
}

for (String x : list) {
    System.out.println(x);
}

Output so far:

391
20141231
24
20
1
0

Which is exactly what I need, but for every line (stored in a String array). Only the last line of the file is stored in the array using the code above.

I've already tried the suggestions here and here. Any suggestions or hints?

Community
  • 1
  • 1
Camelaria
  • 284
  • 6
  • 23
  • May I know why you are using counter>51 ? – Alekhya Vemavarapu Jul 01 '15 at 08:47
  • First 51 lines of the file are not needed. The if-statement lets me process the data after that line. (int counter = 0;) – Camelaria Jul 01 '15 at 08:50
  • 1
    I don't see you storing anything in an array, only printing. Maybe you should create an additional array and instead of overwriting `line` on every iteration, store the values. – Smutje Jul 01 '15 at 08:50
  • 1
    line = br.readLine() is repeated in lines 2 & 5 of your code, this will make your code read two lines for each iteration (which will skip the one that is read first)... You don't need line no.5. You can verify my answer for correct results. – Alekhya Vemavarapu Jul 01 '15 at 09:04
  • Try this. String[] array= new String[list.size()]; array = list.toArray(array); This should help – Alekhya Vemavarapu Jul 01 '15 at 09:12
  • String[] array= new String[list.size()]; array = list.toArray(array); and String[][] resultArray = new String[counter][6]; resultArray = resultList.toArray(resultArray); are giving NullPointers. I'll trying to figure it out. – Camelaria Jul 01 '15 at 09:16
  • What is the point of using a `List` if it's going to be discarded after reading each line? – Tim Biegeleisen Jul 01 '15 at 09:28
  • 1
    You don't need to add your fixed code. Just accept the answer which helped you to solve your question/problem. Since you did that already, everything is fine. – Tom Jul 01 '15 at 11:41

5 Answers5

4
list = Arrays.asList(line.split("\\s*,\\s*"));

This line just replaces existing elements, so you need to append elements, never do = to add elements to list variable.

Probably this can help:

list.addAll(Arrays.asList(line.split("\\s*,\\s*")));
Alekhya Vemavarapu
  • 1,145
  • 1
  • 10
  • 26
Roman Khlebnov
  • 207
  • 3
  • 12
2

This should work:

try {
    BufferedReader br = new BufferedReader(new FileReader("D:\\a.txt"));
    int counter = 0;
    ArrayList<String> list = new ArrayList<String>();
    for (String line; (line = br.readLine()) != null;) {
        counter++;

        if (counter > 51) {
            line = line.trim();
            list.addAll(Arrays.asList(line.split("\\s*,\\s*")));
        }
    }

    String[] array = new String[list.size()];
    array = list.toArray(array);

    for (int i = 0; i < array.length; i++) {
        System.out.println(array[i]);
    }
} catch(Exception e) {
    System.out.println(e);
}
Tom
  • 16,842
  • 17
  • 45
  • 54
Alekhya Vemavarapu
  • 1,145
  • 1
  • 10
  • 26
2

You should try using this.

    private BufferedReader innerReader;
public List<String> loadFrom(Reader reader)
        throws IOException {
    if(reader == null)
    {
        throw new IllegalArgumentException("Reader not found");
    }
        this.innerReader = new BufferedReader(reader);
    List<String> result = new ArrayList<String>();
    String line;
    try
    {
    while((line = innerReader.readLine()) != null)
    {
        if (line == null || line.trim().isEmpty())
            throw new IllegalArgumentException(
                    "line null");

        StringTokenizer tokenizer = new StringTokenizer(line, ",");
        if (tokenizer.countTokens() < 6)
            throw new IllegalArgumentException(
                    "Token number (<= 6)");
        String n1 = tokenizer.nextToken(",").trim();
        String n2 = tokenizer.nextToken(",").trim();
        String n3 = tokenizer.nextToken(",").trim();
        String n4 = tokenizer.nextToken(",").trim();
        String n5 = tokenizer.nextToken(",").trim();
        String n6 = tokenizer.nextToken(",\n\r").trim();
        StringBuilder sb = new StringBuilder();
        sb.append(n1 + "," + n2 + "," + n3 + "," + n4 + "," + n5 + "," + n6);
        result.add(sb.toString());
    }
    } catch (NoSuchElementException e) {
        throw new  IllegalArgumentException(e);
    }
    return result;
}
Brijesh Bhatt
  • 3,810
  • 3
  • 18
  • 34
Michele Lacorte
  • 5,323
  • 7
  • 32
  • 54
1

If you're using Java7, you could use the new Files API to read the file more easily:

public List<List<String>> readValuesJava7() {
  Path path = Paths.get(URI.create("/tmp/coco.txt"));
  List<String> rawLines = new ArrayList<>();
  try {
    rawLines = Files.readAllLines(path);
  } catch (IOException e) {
    e.printStackTrace();
  }
  List<List<String>> lines = new ArrayList<>();
  for (String rawLine : rawLines) {
    List<String> line = new ArrayList<>();
    for (String col : rawLine.split(","))
      line.add(col.trim());
    lines.add(line);
  }
  return lines;
}

If you're using Java8, you can combine that with the new Streams API like so:

public List<List<String>> readValuesJava8() {
  Path path = Paths.get(URI.create("/tmp/coco.txt"));
  Stream<String> rawLines = Stream.empty();
  try {
    rawLines = Files.lines(path);
  } catch (IOException e) {
    e.printStackTrace();
  }
  return rawLines
      .map(line -> line.split(","))
      .map(cols -> Stream.of(cols).map(String::trim).collect(Collectors.toList()))
      .collect(Collectors.toList());
}
ggalmazor
  • 710
  • 6
  • 18
0

You can use a two dimensional array of String to represent the table you are trying to read. I use an ArrayList to read the file since you won't know how many rows you have until reaching the end of the file. I convert the ArrayList to an array at the end of the code sample.

List<String[]> resultList = new ArrayList<String[]>();
int counter = 0;
try (BufferedReader br = new BufferedReader(new FileReader(path))) {

    for (String line; (line = br.readLine()) != null;) {
        counter++;

        if (counter > 51) {                           // ignore the first 51 lines
            line = br.readLine();
            line = line.trim();
            resultList.add(line.split("\\s*,\\s*"));
        }
    }
}

String[][] resultArray = new String[counter][6];      // convert ArrayList of String[]
resultArray = resultList.toArray(resultArray);        // to an array

Output:

System.out.println(resultArray[0][4]); // prints 67
System.out.println(resultArray[4][1]); // prints 20140101
System.out.println(resultArray[6][2]); // prints 7
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360