【问题标题】:How to read text file to ArrayList of different object types in java?如何在java中将文本文件读取到不同对象类型的ArrayList?
【发布时间】:2015-08-06 16:37:35
【问题描述】:

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

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

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

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

编辑:总而言之,我的问题是:如果我有一个如下所示的文本文件,我如何将其拆分为 4 行,然后将每行拆分为 4 个字符串(或 3 个字符串和 1 个字符)并插入每个字符串到一个 ArrayList 中,这样我最终得到一个由四个 InventoryRow 组成的 ArrayList,如下所示: (“卡萨布兰卡”、“旧”、“Y”、空)

库存行类:

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

【问题讨论】:

  • 不确定您的问题是什么.. 使用 Scanner 阅读 4 次?或者读取整行并使用 3 个空格作为分隔符
  • @RC。问题是当我拆分行时,我最终得到了四个字符串,而不是三个字符串和一个字符。但是我也很难按照您所说的拆分行,然后将我拆分的内容插入到 ArrayList 中。如果你能给我你所说的示例代码,那将非常有帮助。

标签: java object arraylist text-files


【解决方案1】:

你可能需要这样的东西:

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

【讨论】:

  • 对于这一行:videos.add(new InventoryRow(s[0], s[1], s[2].charAt(0), s[3])); 你的意思是改写videos.add(new InventoryRow(split[0], split[1], split[2].charAt(0), split[3])); 吗?但是非常感谢。这很好用。
【解决方案2】:

看起来您正在尝试进行基本的序列化和反序列化。 我将专注于您的 while(run) 循环,以便您能够从文件中填充 ArrayList。您的 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() 将返回一个字符串,如: "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 中。除非您特别希望可用性成为一个字符,否则您可以将其保留为字符串。

【讨论】:

  • 这很有帮助,谢谢。尽管这是“使用获得的字段创建一个 InventoryRow 对象,然后将其添加到您的 while 循环中的 ArrayList ”部分,但我真的被卡住了。我想我现在有了@RC. 的帮助。
猜你喜欢
  • 2014-03-26
  • 1970-01-01
  • 2017-09-08
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多