Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

file-io

tabs

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?

like image 891
user2891092 Avatar asked Oct 24 '13 19:10

user2891092


People also ask

How do you read a text file and store it to an ArrayList in Java?

All you need to do is read each line and store that into ArrayList, as shown in the following example: BufferedReader bufReader = new BufferedReader(new FileReader("file. txt")); ArrayList<String> listOfLines = new ArrayList<>(); String line = bufReader. readLine(); while (line !

How do I add data to an ArrayList in Java?

This Java code reads in each word and puts it into the ArrayList: Scanner s = new Scanner(new File("filepath")); ArrayList<String> list = new ArrayList<String>(); while (s. hasNext()){ list. add(s.


1 Answers

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
like image 113
An SO User Avatar answered Oct 20 '22 18:10

An SO User