JAVA:需要帮助从数据文件中读取数据

时间:2013-11-16 00:55:24

标签: java

我正在从文本文件Book.txt中读取,并尝试创建如下构造的Book对象:

public Book(Person author, String title, String isbn, int year, BookGenre genre){
        this.author = author;
        this.title = title;
        this.isbn = isbn;
        this.year = year;
        this.genre = genre;
    }

以下是输入文件的示例:

   Stieg Larsson 0 "The Girl with the Dragon Tattoo" 0307269752 2001 mystery
    Brandon Stanton 0 "Humans of New York" 1250038820 2013 travel
    Oscar Wilde 0 "The Importance of Being Earnest" 158049580X 1895  comic
    Douglas Hofstadter 0 "Gödel, Escher, Bach: An Eternal Golden Braid" 0465026567 1979 science

我不确定使用0可以提供哪些位于作者姓名之后,所以我可能会删除它们,除非你们知道如何使用它们。

以下是我在文件中使用的代码:

else if(name.equals("Book.txt")){
        ArrayList<Book> p = new ArrayList<Book>();
        BufferedReader br = new BufferedReader(new FileReader("Book.txt"));
        String line = br.readLine();
        while(line != null)
        {
            String [] tokens = line.split("\\s+");
            p.add(new Book(new Person(tokens[0], tokens[1], Integer.parseInt(tokens[2])), tokens[3], tokens[4], Integer.parseInt(tokens[5]), tokens[6]));
            line = br.readLine();
        }
        br.close();
        }

我收到错误消息

Exception in thread "main" java.lang.NumberFormatException: For input string: "with"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:59)
        at java.lang.Integer.parseInt(Integer.java:460)
        at java.lang.Integer.parseInt(Integer.java:510)
        at SortingImplementation.main(SortingImplementation.java:43)

所以我很确定我只是简单地读错了文件。有没有人看到任何可以改变的东西让它更好用?

1 个答案:

答案 0 :(得分:0)

由于您希望将BookGenre作为Book构造函数的最后一个参数并且您将String传递给BookGenre,所以不要首先看到您的代码是如何编译的它。但由于这不是所描述的问题,我们假设String类有一个简单的构造函数接受private Book parseBookFromLine(String line) throws Exception { String [] tokens = line.split("\\s+"); Person author = new Person(tokens[0], tokens[1], Integer.parseInt(tokens[2])); String title = ""; int nextToken = 3; /* * Assume next token starts with quotation marks or throw an exception about * malformed data. */ if (tokens[nextToken].endsWith("\"")) { // Skim away the quotation. String temp = tokens[nextToken++]; title = temp.substring(1, temp.length - 1); } else { /* * Loop and keep updating the title until you find next token with * quotation mark or there are only five tokens left. In the latter case, * if no quotation marks found at the end of current token, throw exception * again about malformed data. */ } return new Book(author, title, tokens[nextToken++], Integer.parseInt(tokens[nextToken++]), new BookGenre(tokens[nextToken++]))); } 来修复问题,而你实际上最终会调用它。

然而,就像BalusC指出的那样,你的问题是你期望标题只是一个单词,而你的示例数据中没有。

如果你真的想通过单词分割文本并解析它们来做到这一点,那么请跟进这种逻辑(不,它不是一个完整的解决方案,因为它需要更多的行,但应该有足够的提示在那里让你弄明白其余的):

{{1}}