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?
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 !
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.
Alright, you need to do the recipe shown below:
BufferedReader
ArrayList<String>
String
variable named lineJustFetched
. String
by calling lineJustFetched.split("\t");
String[]
produced. Check if the token you want to enter into the ArrayList
is not ""
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With