help for writing to files in java
Hi I have created a class named 'Human' that each object of this class has a name and a type which can be student or instructor. I have created another class main which creates object of Human and assign type and name to th开发者_开发知识库e objects and add that objects into a linkedList. Now I want to write this linkedList into a file,but i dont know how. i must write both objects and their type into that linkedList. i have created following as the Main class but I have problem in the writing file parts. would you please guide me?
public class Testing {
public static LinkedList<Human> link =new LinkedList<Human>();
static FileOutputStream fop;
public static void main(String args[])
{
File f=new File("textfile1.txt");
try {
fop=new FileOutputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Human hm = new Human();
Human hum = new Human();
hm.setName("Anna");
hm.setType("Student");
hum.setName("Elvis");
hum.setType("Instructor");
link.add(hm);
link.add(hum);
for (Human h : link) {
fop.write(h.getType());
fop.write(h);
}
}
}
Look at java.io.PrintStream
PrintStream p = new PrintStream(fop);
for (Human h : link) {
p.println(h.getType());
p.println(h);
}
p.close();
Assuming you have implemented a toString method for Human.
An easy and working solution for your problem would be creating a simple "CSV" file, this would be a readable representation of your Human
objects and look like:
Anna;Student
Elvis;Instructor
You can achieve this with doing:
for (Human h : link) {
String line = h.toString() + ";" + h.getType() + "\n";
fop.write(line.getBytes());
}
If you want to write the Objects to a file, you need to use serialization. Make the Human object to implement Serializable
interface and then refer how to write the object to an output stream using serialization.
精彩评论