每行文本的对象

时间:2016-05-08 22:40:21

标签: java oop io

public class library {
  library() {
    ArrayList<book> books = new ArrayList<book>();
  }

public void read() throws Exception {
    String thisLine = null;
    try {
        BufferedReader br = new BufferedReader(new FileReader("c:/booklist.txt"));
        while ((thisLine = br.readLine()) != null) {
            System.out.println(thisLine);

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

public static void main(String[] args) throws Exception {
    library lib = new library();
    lib.read();
}
}

我正在从文本文件中读取各种书籍的标题,我需要为每个标题(文本行)创建一个单独的书类对象。该类只有一个属性 - 字符串标题。我会用你的帮助人员;)

2 个答案:

答案 0 :(得分:2)

public void read() throws Exception {
    String thisLine = null;
    try {
        BufferedReader br = new BufferedReader(new FileReader("c:/booklist.txt"));
        while ((thisLine = br.readLine()) != null) {
            System.out.println(thisLine);
            Book b = new Book(thisLine);
            books.add(b);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

所以你将有一个充满了由标题

标识的书籍的arraylist

答案 1 :(得分:1)

您的Book课程应该如下所示:

public class Book {

    String title;

    public Book(String title) { //constructor
        this.title = title; //sets the value of title to the String passed to the constructor
    }
}

Oussema Aroua发布的答案显示了如何使用此课程创建ArrayListBook个对象。