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

时间:2015-08-06 16:37:36

标签: java object arraylist text-files

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

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

我尝试过创建一个CSV并使用split()函数,但我无法弄清楚如何使用它插入到ArrayList中,因为我最终得到一行中的四个字符串而不是(String,String,字符,字符串)。我甚至尝试更改当前的ArrayList,以便每个元素都是一个字符串,但我仍然不确定如何使其工作。

任何帮助都会非常感激。如果您需要更多信息,请与我们联系。

编辑:总结一下,我的问题是:如果我有一个如下所示的文本文件,我该如何将其分成4行,然后将每行分成4个字符串(或3个字符串和1个字符)并插入每个字符串进入一个ArrayList,这样我最终得到一个四个InventoryRow的ArrayList,如下所示: (“Casablanca”,“Old”,“Y”,null)

库存行类:

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

2 个答案:

答案 0 :(得分:2)

你可能需要这样的东西:

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

答案 1 :(得分:1)

看起来你正在尝试进行基本的序列化和放大反序列化。 我将重点关注while(run)循环,以便您能够从文件中填充ArrayList。您的InventoryRow类足够好,并且数组列表已正确参数化。

import java.io.*;
import java.util.*;
import edu.stanford.nlp.io.*;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.trees.*;
import edu.stanford.nlp.semgraph.*;
import edu.stanford.nlp.trees.TreeCoreAnnotations.*; 
import edu.stanford.nlp.util.*;


public class StanfordSafeLineExample {

        public static void main (String[] args) throws IOException {
            // build pipeline
            Properties props = new Properties();
            props.setProperty("annotators","tokenize, ssplit, pos, depparse");
            props.setProperty("ssplit.eolonly","true");
            StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
            // open file
            BufferedReader br = new BufferedReader(new FileReader(args[0]));
            // go through each sentence
            for (String line = br.readLine() ; line != null ; line = br.readLine()) {
                try {
                    Annotation annotation = new Annotation(line);
                    pipeline.annotate(annotation);
                    ArrayList<String> edges = new ArrayList<String>();
                    CoreMap sentence = annotation.get(CoreAnnotations.SentencesAnnotation.class).get(0);
                    SemanticGraph tree = sentence.get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class);
                    System.out.println("---");
                    System.out.println("sentence: "+line);
                    System.out.println(tree.toString(SemanticGraph.OutputFormat.READABLE));
                } catch (Exception e) {
                    System.out.println("---");
                    System.out.println("Error with this sentence: "+line);
                }
            }

        }
}

s.next()将返回一个String,如: &#34;名称;类型;一个;日期&#34;您需要通过执行以下操作将其拆分为分隔符:

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

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