aspose file tools*
The moose likes Beginning Java and the fly likes File IO Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "File IO" Watch "File IO" New topic
Author

File IO

Lenny Peter
Ranch Hand

Joined: Apr 22, 2008
Posts: 52
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

Joined: Mar 02, 2005
Posts: 443
    
    1

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

Joined: Oct 13, 2005
Posts: 36575
    
  16
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

Joined: Apr 22, 2008
Posts: 52
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

Joined: Jul 11, 2001
Posts: 14112
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?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36575
    
  16
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: File IO
 
Similar Threads
# of lines in a file?
Reading from file A, writing to file B
FileIO
comparing two files
Java BufferedReader and BufferedWriter