user2891092 user2891092 - 1 year ago 85
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(){
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:

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

Answer Source

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.


import java.util.ArrayList;

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

                lineJustFetched = buf.readLine();
                if(lineJustFetched == null){  
                    wordsArray = lineJustFetched.split("\t");
                    for(String each : wordsArray){

            for(String each : words){


        }catch(Exception e){


likes to play tennis
likes to solve crime
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download