I have a project and the instructions are a bit unclear. I was given an abstract class (Java) with : public abstract void toTxtFile(PrintWriter outFile);
The only other instructions relating to that outFile corresponds with staffMember object which should be written to file. I wrote the below but not sure if it is correct
public void toTxtFile(PrintWriter outFile) {
try
{
FileOutputStream fout = new FileOutputStream("pay.txt");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(outFile);
}
catch (IOException e)
{
throw new RuntimeException("Could not write Exception to file", e);
}
catch (Exception e)
{
System.out.println("There was an error");
}
}
You misunderstood the instructions. A PrintWriter can't be written to a file, and that's not what the (admittedly badly named) method should do.
What it should most probably do is to write the state of the StaffMember object to the given PrintWriter.
So, in short, the method should look like
public void toTxtFile(PrintWriter outFile) {
outFile.println(this.name);
outFile.println(this.age);
...
}
This is similar to me giving you my phone and asking you to spell your name and address to the phone. A PrintWriter is just a way to communicate your own personal information to someone else.
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.