user2891092 user2891092 - 1 year ago 57
Java Question

JAVA - how to read specific line then put it in arraylist

Hi so i have this project that requires me to write the code in java lets say i have this txt file:

GoodTitle Description
Gold The shiny stuff
Wheat What wheaties are made of
Wood To make more ships
Spices To disguise the taste of rotten food
Tobacco Smoko time
Coal To make them steam ships go
Coffee Wakes you up
Tea Calms you down

all i want to do is to put the left side of the text (goodtitle,gold,wheat,wood,etc) into an arraylist and the right side of the text(description,the shiny stuff) into another array list. this is my current code:

public void openFile(){
x = new Scanner(new File("D://Shipping.txt"));
catch (Exception e){
System.out.println("File could not be found");
public void readFile(){
while (x.hasNextLine()){
String a =;
ArrayList<String> list = new ArrayList<String>();
while (x.hasNext()){
System.out.printf("%s \n", list);
public void closeFile(){

probably it need some modification on readFile as i still confuse on how to do it. thanks in advance...

NOTE=I am not allowed to change the content of the txt file.
in my current code i still put the whole thing into 1 arraylist because i am unable to split them.

do i need toString method?because i have no idea how to do it.
thanks in advance...

Answer Source

You have to read the left side into one list and the right side into another.

This code isn't right because doesn't actually return one column. How could it know what one column is? But it should give you an idea of how to do it.

ArrayList<String> listL = new ArrayList<String>();
ArrayList<String> listR = new ArrayList<String>();
while (x.hasNextLine()){
    if (x.hasNext()){
    } else {

    if (x.hasNext()){
    } else {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download