如何通过阅读文本文件创建项目对象? [英] How to create item objects from reading a text file?

查看:148
本文介绍了如何通过阅读文本文件创建项目对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从文本文件中读取数据并使用它创建项目对象。
Item Objects有字段String title,String formatt,boolean onLoan,String loanedTo和String dateLoaned。在我的save()方法中,我将每个对象打印到新行中的文本文件中,并且字段由$(美元符号)分隔。如何逐行读取文本文件并从每行创建一个新对象并将其添加到数组中。

I'm trying to read data from a text file and create Item Objects with it. Item Objects have fields String title, String formatt, boolean onLoan, String loanedTo and String dateLoaned. In my save()method, I print every object to a text file in a new line and the fields are seperated by "$" (dollar sign). How can I read the text file line by line and create a new object from each line and add it to an array.

TextFile示例:

TextFile Example:

StarWars $ DVD $ false $ null $ null

StarWars$DVD$false$null$null

外国人$ Bluray $ true $ John $ Monday

Aliens$Bluray$true$John$Monday

public void save() {
    String[] array2 = listForSave();
    PrintWriter printer = null;

      try {
          printer = new PrintWriter(file);

            for (String o : array2) {
            printer.println(o);
            }
            printer.close();
        } catch ( IOException e ) {
            e.printStackTrace();
        }

}
public void open(){
    try{

    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    StringBuffer stringBuffer = new StringBuffer();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        stringBuffer.append(line);
        stringBuffer.append("\n");
    }
    fileReader.close();
    System.out.println("Contents of file:");
    System.out.println(stringBuffer.toString());

    }catch ( IOException e ) {
        e.printStackTrace();
    }


}

谢谢大家。这是我的最终代码:

Thanks everyone. Here's my final code:

public void open(){
    try{

    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String line;
    String[] strings;
    while ((line = bufferedReader.readLine()) != null) {
        strings = line.split("\\$");
        String title = strings[0];
         String format = strings[1];
         boolean onLoan = Boolean.parseBoolean(strings[2]);
         String loanedTo = strings[3];
         String dateLoaned = strings[4];

         MediaItem superItem = new MediaItem(title,format, onLoan,loanedTo,dateLoaned);
         items.add(superItem);

    }
    fileReader.close();


    }catch ( IOException e ) {
        e.printStackTrace();
    }


}


推荐答案

String line = // input line e.g. "Aliens$Bluray$true$John$Monday"
String[] strings = line.split("\\$"); // use regex matching "$" to split
String title = strings[0];
String formatt = strings[1];
boolean onLoan = Boolean.parseBoolean(strings[2]);
String loanedTo = strings[3];
String dateLoaned = strings[4];
// TODO: create object from those values

也许你需要处理 null 以不同方式(如果您希望将String null转换为 null );请注意,您无法区分 null null是否已保存。

Maybe you need to handle null differently (in case you want the String "null" to be converted to null); note that you can't distinguish if null or "null" was saved.

此函数将null转换为 null 并返回相同的字符串:

This function converts "null" to null and returns the same string otherwise:

String convert(String s) {
    return s.equals("null") ? null : s;
}



将对象读取到数组



由于在阅读所有行之前你不知道元素的数量,你必须解决这个问题:

Reading the objects to an array

Since you don't know the number of elements before reading all lines, you have to work around that:


  1. 将文件中的对象数写为第一行,这样可以在读取第一个对象之前创建数组。 (使用 Integer.parseInt(String)将第一行转换为int):

  1. Write the number of objects in the file as first line, which would allow you to create the array before reading the first object. (Use Integer.parseInt(String) to convert the first line to int):

public void save() {
    String[] array2 = listForSave();
    PrintWriter printer = null;

      try {
          printer = new PrintWriter(file);
          printer.println(array2.length);
            for (String o : array2) {
                printer.println(o);
            }
            printer.close();
        } catch ( IOException e ) {
            e.printStackTrace();
        }

}
public void open(){
    try{

    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    StringBuffer stringBuffer = new StringBuffer();
    int arraySize = Integer.parseInt(stringBuffer.readLine());
    Object[] array = new Object[arraySize];
    int index = 0;
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        // split line and create Object (see above)
        Object o = // ...
        array[index++] = o;
    }
    //...
    }catch ( IOException e ) {
        e.printStackTrace();
    }
    //...
}

这篇关于如何通过阅读文本文件创建项目对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆