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.

5
  • You do realise that you are splitting on - right now... Commented Jul 18, 2017 at 19:04
  • 1
    For your problem, i think something like a List would be more appropriate than some arrays Commented Jul 18, 2017 at 19:05
  • "In a separate array", you mean a brand new array for each word? Commented Jul 18, 2017 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 Commented Jul 18, 2017 at 19:09
  • Possible duplicate of Java: splitting a comma-separated string but ignoring commas in quotes Commented Jul 18, 2017 at 19:35

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

3 Comments

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 this mean that you don't have a line is not match string1/string2 can you please share all your file?
Thanks I have sorted it out now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.