简体   繁体   中英

Reading and storing data from text file in java

Text File

Book
VAM-001
Dracula
Stoker, B
14
true
null
Book
WIW-001
The Wind In the Willows
Grahame, K.
14
true
null
Book
WAP-001
War and Peace
Tolstoy, L.
14
true
null
Book
MIL-001
The Girl with the Dragon Tattoo
Larsen, S.
14
true
null
Book
CRU-001
The Crucible
Miller, A.
14
true
null
Book
LTR-001
The Fellowship of the Rings
Tolkien, J. R. R.
14
true
null
Book
WOT-001
The Eye of The World
Jordan, R.
14
true
null
Textbook
JAV-001
Introduction to Java Programming
Liang, D.
2
true
null
COSC1073 COSC1284 COSC2531 COSC1295
Textbook
DBC-001
Fundamentals of Database Systems
Elmasri, R. & Navathe, S.
2
true
null
ISYS1057
Textbook
WST-001
HTTP: The Definitive Guide
Gourley, D. & Totty, B.
2
true
null
COSC1285
Textbook
AIN-001
Artificial Intelligence - A Modern Approach.
Russell, S. & Norvig, P.
2
true
null
COSC1127
Textbook
ITP-001
Introduction to Computing and Programming in Python.
Guzdial, M. & Ericson, B.
2
true
null
COSC1519
Book
VAM-002
Interview with a Vampire
Rice, A.
14
true
null
Book
MIL-002
The Girl Who Played with Fire
Larsen, S.
14
true
null
Book
WIZ-001
A Wizard of Earthsea
Le-Guin, U. K.
14
true
null
Book
WIZ-002
Harry Potter and the Deathly Hallows
Larsen, S.
14
true
null
Book
BOU-001
The Bourne Identity
Ludlum, R.
14
true
null
Book
DIC-001
A Tale of Two Cities
Dickens, C.
14
true
null
Book
TGG-001
The Great Gatsby
Fitzgerald, F. S.
14
true
null
Book
MOD-001
Moby Dick
Melville, H.
14
true
null

Java Code

BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append("\n");
        line = br.readLine();
    }
    String[] books = sb.toString().split("\n");

    System.out.println(Arrays.toString(books));

} finally {
    br.close();
}

I have successful read the file, but I don't know how to parse the data. I have to store books in one class and textbooks in a different class. Every entry has 6 fields:

  • book id
  • title
  • author
  • loan days
  • availability(a boolean)
  • member code(can be null if not occupied)

The delimiter in this text file is a new line character ( \\n ). Please help me. Thanks in advance!

Create Book class add book id, title, author, loan days, availability and member code fields to it. Then drive TextBook class from Book and and add it the seventh field (COSC1127) that regular books don't have. While you are reading the lines when you read line "Book" create a book object and fill it, when you read a "TextBook" create a TextBook and fill that. Instead of keeping a String array create two Lists for Book and TextBook and add your objects to lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM