简体   繁体   English

如何在Java中将文本文件读取到不同对象类型的ArrayList?

[英]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. 我是编程的初学者,我需要一些帮助,试图从文本文件读取到包含不同类型对象的ArrayList中。 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. 我创建了一个程序来控制视频清单,目前我已将其硬编码到程序中的ArrayList中,但是我想对此进行更改,以便每次程序运行时,该程序都会从​​包含清单和将其转换为ArrayList而不是从程序中已经存在的ArrayList中读取。 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). 我遇到的问题是我的ArrayList(视频)包含(字符串,字符串,字符,字符串)。 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. 我不知道如何更改我拥有的代码,以便扫描程序将文本文件中的每一行拆分为适当的块(用于标题,类型,可用性和返回日期),然后将每个单独的块插入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). 我尝试创建一个CSV并使用split()函数,但由于无法在一行中包含四个字符串而不是(字符串,字符串,字符,字符串),因此无法弄清楚如何使用该字符串插入ArrayList )。 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. 我什至尝试更改当前的ArrayList,以使每个元素都是一个字符串,但是我仍然不确定如何使它工作。

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) 编辑:总而言之,我的问题是:如果我有一个文本文件,如下所示,如何将其拆分为4行,然后将每一行拆分为4个字符串(或3个字符串和1个字符),并将每个字符串插入ArrayList中这样我就得到了四个这样的InventoryRow的ArrayList :(“ 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

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])); 
}

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. 我将重点放在while(run)循环上,以便您可以从文件中填充ArrayList。 Your InventoryRow class is good enough and the array list is correctly parameterized. 您的InventoryRow类足够好,并且数组列表已正确参数化。

//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: s.next()将返回一个字符串,例如:“ name; type; a; date”,您需要通过执行以下操作在分隔符上拆分该字符串:

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. 使用获取的字段创建一个InventoryRow对象,然后将其添加到while循环中的ArrayList中。 Unless you specifically want the availability to be a character you could leave it as a string. 除非您特别希望可用性是一个字符,否则可以将其保留为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM