如何将文本文件读取到 java 中不同 object 类型的 ArrayList?

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

我是编程初学者,我需要一些帮助来尝试将文本文件读入包含 objects 不同类型的 ArrayList。我创建了一个程序来控制视频清单,我目前已将其硬编码到程序中的 ArrayList 中,但我想更改此设置,以便每次程序运行时,程序都会从​​包含清单的文本文件中读取和将其转换为 ArrayList,而不是从程序中已有的 ArrayList 中读取。我已经添加了一个函数,可以在程序退出后将清单写入文本文件,但我似乎无法从文本文件中读取它。

我遇到的问题是我的 ArrayList(视频)包含(字符串、字符串、字符、字符串)。我不知道如何更改我的代码,以便扫描仪将文本文件中的每一行拆分为适当的块(标题、类型、可用性和 return 日期),然后将每个单独的块插入适当的放在 ArrayList 中。我希望这是有道理的。

我试过创建一个 CSV 文件并使用 split() 函数,但我不知道如何使用它插入到 ArrayList 中,因为我最终在一行中有四个字符串而不是 (String,字符串、字符、字符串)。我什至尝试更改我当前的 ArrayList,以便每个元素都是一个字符串,但我仍然不确定如何实现它。

任何帮助将不胜感激。如果您需要更多信息,请告诉我。

编辑:总而言之,我的问题是:如果我有一个如下所示的文本文件,我如何将它分成 4 行,然后将每行分成 4 个字符串(或 3 个字符串和 1 个字符)并插入将每个字符串放入一个 ArrayList 中,这样我最终得到一个包含四个 InventoryRow 的 ArrayList,如下所示: ("Casablanca", "Old", 'Y', 空)

库存行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;
}
}

主要方法(包括我当前不起作用的代码):

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

}

我写入文本文件的代码:

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 + "'");
    }
}

我的文本文件如下所示:

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

您似乎正在尝试进行基本的序列化和反序列化。 我将专注于您的 while(运行) 循环,以便您能够从文件中填充 ArrayList。您的 InventoryRow class 足够好并且数组列表已正确参数化。

//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() 将 return 一个像这样的字符串: "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.

使用获取的字段创建一个 InventoryRow 对象,然后将其添加到 while 循环中的 ArrayList。除非您特别希望可用性是一个字符,否则您可以将其保留为字符串。

您可能需要这样的东西:

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