Ini
Ini

Reputation: 87

How to read text file to ArrayList of different object types in java?

I'm a beginner to programming and I need some help trying to read from a text file into an ArrayList that contains objects of different types. I've created a program that controls an inventory of videos which I currently have hard coded into an ArrayList in the program but I would like to change this so every time the program runs, the program reads from the text file which contains the inventory and converts that into an ArrayList instead of reading from the ArrayList that is already in the program. I've already added a function that writes the inventory to the text file once the program has quit but I can't seem to get it to read from the text file.

The problem I'm having is that my ArrayList (videos) contains (String, String, Character, String). I don't know how to change the code I have so that scanner splits each line in the text file into the appropriate chunks (for title, type, availability and return date) and then inserts each individual chunk into the appropriate place in the ArrayList. I hope that made sense.

I've tried creating a CSV and using the split() function but I couldn't figure out how to use that to insert into an ArrayList as I end up with four strings in a line rather than (String, String, Character, String). I've even tried changing my current ArrayList so that every element is a string but I still wasn't sure how to make that work.

Any help would be really appreciated. Let me know if you need further information.

EDIT: To sum up, my question is: if I have a text file as seen below, how do I split that into 4 lines and then each line into 4 strings (or 3 strings and 1 character) and insert each string into an ArrayList so that I end up with an ArrayList of four InventoryRow's like this: ("Casablanca", "Old", 'Y', null)

Inventory Row Class:

class InventoryRow {
private String name;
private String type;
private Character availability;
private String returndate;

public InventoryRow(String name, String type, Character availability,
        String returndate) {
    this.name = name;
    this.type = type;
    this.availability = availability;
    this.returndate = returndate;
}

public String getReturndate() {
    return returndate;
}

public void setReturndate(String returndate) {
    this.returndate = returndate;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public Character getAvailability() {
    return availability;
}

public void setAvailability(Character availability) {
    this.availability = availability;
}

public String toString() {
    return name + "   " + type + "   " + availability + "   " + returndate;
}
}

Main method (including my current code which doesn't work):

public class InventorySort {

public static void main(String[] args) throws ParseException, JSONException, FileNotFoundException {
    /*
     * List<InventoryRow> videos = new ArrayList<InventoryRow>();
     * 
     * videos.add(new InventoryRow("Casablanca", "Old", 'Y', null));
     * videos.add(new InventoryRow("Jurassic Park", "Regular", 'N',
     * "31/07/2015")); videos.add(new InventoryRow("2012", "Regular", 'Y',
     * null)); videos.add(new InventoryRow("Ant-Man", "New", 'Y', null));
     */

    // Get's today's date and adds three to it = return date
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat dateReturn = new SimpleDateFormat("dd/MM/yyyy", Locale.UK);
    cal.add(Calendar.DATE, 3);

    Scanner input = new Scanner(System.in);
    boolean run = true;

    while (run) {
        // Read from text file
        Scanner s = new Scanner(new File("videos.txt"));
        List<InventoryRow> videos = new ArrayList<InventoryRow>();
        while (s.hasNext()) {
            videos.add(new InventoryRow(s.next(), null, null, null));
        }
        s.close();

        // Output the prompt
        System.out.println("Do you want to list, rent, check, return, add, delete or quit?");

        // Wait for the user to enter a line of text
        String line = input.nextLine();

        // List, rent and check functions
        // List function
        if (line.equals("list")) {
            // Sort videos alphabetically
            list(videos);
            // Rent function
        } else if (line.equals("rent")) {
            rent(videos, cal, dateReturn, input);
            // Check function
        } else if (line.equals("check")) {
            check(videos, input);
            // If anything else is entered
        } else if (line.equals("return")) {
            returnVideo(videos, input);
        } else if (line.equals("add")) {
            add(videos, input);
        } else if (line.equals("delete")) {
            delete(videos, input);
        } else if (line.equals("quit")) {
            run = false;
            writeFile(videos);
        } else {
            other();
        }
    }

}

The code I have for writing to the text file:

private static void writeFile(List<InventoryRow> videos) {
    String fileName = "videos.txt";

    try {
        FileWriter fileWriter = new FileWriter(fileName);

        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        for (InventoryRow ir : videos) {

            bufferedWriter.write(ir.toString() + System.getProperty("line.separator"));

        }
        bufferedWriter.close();
    } catch (IOException ex) {
        System.out.println("Error writing to file '" + fileName + "'");
    }
}

My text file looks like this:

2012   Regular   Y   null
Ant-Man   New   Y   null
Casablanca   Old   Y   null
Jurassic Park   Regular   N   31/07/2015

Upvotes: 0

Views: 7792

Answers (2)

user180100
user180100

Reputation:

You probably need something like this:

List<InventoryRow> videos = new ArrayList<InventoryRow>();
while (s.hasNextLine()) {
    String[] split = s.nextLine().split("   ");
    // TODO: make sure the split has correct format

    // x.charAt(0) returns the first char of the string "x"
    videos.add(new InventoryRow(split[0], split[1], split[2].charAt(0), split[3])); 
}

Upvotes: 2

Sid
Sid

Reputation: 463

It looks like you are trying to do basic serialization & deserialization. I will focus on your while(run) loop so that you are able to populate the ArrayList from the file. Your InventoryRow class is good enough and the array list is correctly parameterized.

//This creates an object to read the file
Scanner s = new Scanner(new File("videos.txt"));


while (s.hasNext()) {
   //This is where the problem is:
   videos.add(new InventoryRow(s.next(), null, null, null));
}

s.next() will return a String like: "name;type;a;date" you need to split this on your separator character by doing something like:

String line = s.next();
String[] fields = line.split(","); //use your choice of separator here & check how to use the split method.

Create a InventoryRow object with the obtained fields and then add that to the ArrayList in your while loop. Unless you specifically want the availability to be a character you could leave it as a string.

Upvotes: 1

Related Questions