user2891092 user2891092 - 1 month ago 9
Java Question

Read a file separated by tab and put the words in an ArrayList

I am doing a self learning exercise to help me understand more about Java, but I am stuck at this question. I have the following txt file:

Name Hobby
Susy eat fish
Anna gardening
Billy bowling with friends


Note: name and hobby are separated by tab

What is the best way to read all the line and put it in arraylist(name,hobby). The tricky part is that

eat fish or bowling with friends


has white spaces and it must be put under one array and obviously I cannot hardcode it. Here is my current code:

public void openFile(){
try{
FileInputStream fstream = new FileInputStream("textfile.txt");
// use DataInputStream to read binary NOT text
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> hobbies = new ArrayList<String>();
String lineJustFetched;
while ((lineJustFetched = br.readLine()) != null) {
String[] tokens = lineJustFetched.split(" \t");


I got an error:


java.lang.StringIndexOutOfBoundsException: String index out of range:
-1


I suspect counting the index is not very useful on a tab.
Any idea?

Answer

Alright, you need to do the recipe shown below:

  1. Create a BufferedReader
  2. Create an ArrayList<String>
  3. Start reading data into a String variable named lineJustFetched.
  4. Split the String by calling lineJustFetched.split("\t");
  5. Iterate over the String[] produced. Check if the token you want to enter into the ArrayList is not ""
  6. If not, add the word to the ArrayList

You specify that you need to split based on \t values so white spaces won't be an issue.

SSCCE

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

public class WordsInArray {
    public static void main(String[] args) {
        try{
            BufferedReader buf = new BufferedReader(new FileReader("/home/little/Downloads/test"));
            ArrayList<String> words = new ArrayList<>();
            String lineJustFetched = null;
            String[] wordsArray;

            while(true){
                lineJustFetched = buf.readLine();
                if(lineJustFetched == null){  
                    break; 
                }else{
                    wordsArray = lineJustFetched.split("\t");
                    for(String each : wordsArray){
                        if(!"".equals(each)){
                            words.add(each);
                        }
                    }
                }
            }

            for(String each : words){
                System.out.println(each);
            }

            buf.close();

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

Output

John
likes to play tennis
Sherlock
likes to solve crime