0

I want to read the contents of a text file, split on a delimiter and then store each part in a separate array.

For example the-file-name.txt contains different string all on a new line:

football/ronaldo
f1/lewis
wwe/cena

So I want to read the contents of the text file, split on the delimiter "/" and store the first part of the string before the delimiter in one array, and the second half after the delimiter in another array. This is what I have tried to do so far:

try {

    File f = new File("the-file-name.txt");

    BufferedReader b = new BufferedReader(new FileReader(f));

    String readLine = "";

    System.out.println("Reading file using Buffered Reader");

    while ((readLine = b.readLine()) != null) {
        String[] parts = readLine.split("/");

    }

} catch (IOException e) {
    e.printStackTrace();
}

This is what I have achieved so far but I am not sure how to go on from here, any help in completing the program will be appreciated.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
qwerty
  • 37
  • 6
  • You do realise that you are splitting on `-`  right now... – litelite Jul 18 '17 at 19:04
  • 1
    For your problem, i think something like a [`List`](https://docs.oracle.com/javase/7/docs/api/java/util/List.html) would be more appropriate than some arrays – litelite Jul 18 '17 at 19:05
  • "In a separate array", you mean a brand new array for each word? – Rabbit Guy Jul 18 '17 at 19:07
  • @rabbitguy all the words before the delimiter in one array, and all the words after the delimiter in another array. sorry if i wasnt clear on this – qwerty Jul 18 '17 at 19:09
  • Possible duplicate of [Java: splitting a comma-separated string but ignoring commas in quotes](https://stackoverflow.com/questions/1757065/java-splitting-a-comma-separated-string-but-ignoring-commas-in-quotes) – worker_bee Jul 18 '17 at 19:35

1 Answers1

1

You can create two Lists one for the first part and se second for the second part :

List<String> part1 = new ArrayList<>();//create a list for the part 1
List<String> part2 = new ArrayList<>();//create a list for the part 2

while ((readLine = b.readLine()) != null) {
    String[] parts = readLine.split("/");//you mean to split with '/' not with '-'

    part1.add(parts[0]);//put the first part in ths list part1
    part2.add(parts[1]);//put the second part in ths list part2
}

Outputs

[football, f1, wwe]
[ronaldo, lewis, cena]
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • Thanks for the reply, but when I run the program I get an Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:1 coming from this line part2.add(parts[1]); – qwerty Jul 18 '17 at 19:23
  • @qwerty this mean that you don't have a line is not match `string1/string2` can you please share all your file? – Youcef LAIDANI Jul 18 '17 at 19:26
  • Thanks I have sorted it out now – qwerty Jul 18 '17 at 19:31