• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

File IO

 
Lenny Peter
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I need some help...
How can I use FileWrite and FileReader in my Student class?
Should I make an extra class or I can add those to Student class?






This is my class:

 
Rajkamal Pillai
Ranch Hand
Posts: 445
1
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Leni,

Since this looks like a simple program I'd say that you might consider adding two more methods, one for reading from the file and the other for writing to it? Don't see much sense in another helper class for this purpose.

Cheers,
Raj.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50278
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Disagree. File reading is not a responsibility of the Student class, and creating a helper class will make for better design. Also you can reuse the helper class.

But you may find it easier to use a java.util.Scanner for reading and a java.util.Formatter for writing, as long as you don't need to append details to your files.

Change the try-catch to read like thisThe use of "finally" ensures that the reader closes, even when there is an Exception. You need two nested try blocks. Similarly with a writer.
 
Lenny Peter
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks

But I need more help :roll:

I have a class Student and I will make an extra class StudentIO with private Student student?
And?








 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A well known way would be to write a Data Access Object. See http://java.sun.com/blueprints/patterns/DAO.html

That is, you could have a StudentFilesystemDAO, with methods like

Student getStudent(String name)
Student[] getAllStudents()
void saveStudent(Student student)

etc.pp.

Does that help?
 
Campbell Ritchie
Sheriff
Pie
Posts: 50278
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Leni Kravitskki:
Thanks
And?

public void what? openFile()?
Whatever the method your original reading code quoted earlier would have been in.
And don't use System.out for printing Exceptions, use System.err.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic