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?