Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I write to a file using FileOutputStream???

Status
Not open for further replies.

Oxymoron

Technical User
Dec 17, 2000
168
GB
hi.
I'm trying to print an object to a file using:

FileOutputStream fos = new FileOutputStream("client.tmp");
ObjectOutputStream put = new ObjectOutputStream(fos);

then calling a method writeObject()

put.writeObject(customer1);

However, I keep getting errors either saying that I have to declare exceptions which will be thrown, which I dont understand because both of the above instances are attributes and I dont know how to inicate that they will throw exceptions, except through the method specification.

When I can get it to compile by making the instances inside the method, the program runs until it comes to writing the file, then a load of NotSerializableExceptions pop up.
To remedy this I have added ' import java.io.Serializable ' to class Client is the class of the instance 'customer1' I am trying to write to file, to make it a serializable instance....but still get the same errors.

Pllllllllleeeeeeeeeeeaaaseee, if anyone knows of a way I'd be very grateful! preferably if you could tell me what I'm doing wrong so I can learn, t'd b good!!

cheers every1!!!!!
JoE
we are all of us living in the gutter.
But some of us are looking at the stars.
 
The compile errors you're getting are telling you that the code you wrote is capable of throwing exceptions. For instance, the line

FileOutputStream fos = new FileOutputStream("client.tmp");

is capable of throwing a FileNotFoundException. You have to handle the exceptions, either by enclosing the code in a try/catch block like this:

try
{
FileOutputStream fos = new FileOutputStream("client.tmp");
ObjectOutputStream put = new ObjectOutputStream(fos);
put.writeObject(customer1);
}
catch (Exception e)
{
// Do something with exception, like print it to the console or something
}

... or, you can simple add a "throws" clause to the class definition and put the try/catch block in the object that calls this class...

public class foo throws Exception


As you discovered, though, you have a second problem - the customer1 object is not serializable. To make it serializable, the class Client must implement the Serializable interface.

Hope this helps.
 
how do i implement the serializable interface?
what code statements do I need?

cheers for all ur help idarke! :)

JoE
we are all of us living in the gutter.
But some of us are looking at the stars.
 
"how do i implement the serializable interface? "

it is part of your class declaration.

Code:
public class foo implements Serializable

If you can get your hands on the book "Java 2, Third Edition" this will answer all your questions and help you avoid many other pitfalls. ----------------------------------------
There are no onions, only magic
----------------------------------------
 
grrr,
I've changed my code so in theory there should be NOTHING wrong with writing an object to a file.
the file compiles and runs, but when it comes to writing the file I get these errors:
-------------------command prompt output-------------------
********** Add a New Client **********

Forename: rdt
Surname: dfg
Sex (m/f): m
Exception in thread "main" java.io.NotSerializableException: java.io.BufferedReader
at java.io_ObjectOutputStream.writeObject0(ObjectOutputStream.java:1054)
at java.io_ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1330)
at java.io_ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1302)
at java.io_ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1245)
at java.io_ObjectOutputStream.writeObject0(ObjectOutputStream.java:1052)
at java.io_ObjectOutputStream.writeObject(ObjectOutputStream.java:278)
at Client.writeIt(Client.java:85)
at Client.addClientMenu(Client.java:76)
at Menu.mainMenu(Menu.java:35)
at Menu.main(Menu.java:77)

C:\Java\CompSci\Project1>
----------------------------------------------------------

What is wrong with the code I have?????
------------------------Client.java------------------------
import java.io.*;


public class Client implements Serializable
{
private static int MALE = 0;
private static int FEMALE = 1;

private String forename;
private String surname;
private int sex;
private double height;
private int age;
private Residence address;
private String description;
private String phone;
private String email;
private Vacation destination;

public BufferedReader input = new BufferedReader(
new InputStreamReader(System.in));

/**
*Constructor assigns values to instance variables
*@param theForename The forename of client
*@param theSurname The surname of client
*/
public Client(String theForename,
String theSurname)
{
forename = theForename;
surname = theSurname;
}

public void addClientMenu() throws IOException
{
System.out.println("\n\t********** "
+ "Add a New Client"
+ " **********\n");

System.out.print("Forename: ");
String firstName = input.readLine();
System.out.print("Surname: ");
String lastName = input.readLine();
Client temp = new Client(firstName, lastName);
System.out.print("Sex (m/f): ");
//do
//{
char gender = ' ';
gender = (input.readLine().toLowerCase().charAt(0));
switch (gender)
{
case 'm':
temp.setSex(0);
break;

case 'f':
temp.setSex(1);
break;

default:
System.out.println("\t\tSorry, invalid entry. "
+ "Enter either M or F");
}
//} while (gender != 'm' | 'f');

this.writeIt(temp);
}

public void writeIt(Client aClient) throws IOException
{
File clientFile = new File("clientFile.tmp");
ObjectOutputStream put = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(clientFile)));
put.writeObject(aClient);
}
-----------------------------------------------------------

If anyone can find anything wrong with this, pllleeeeeease tell me. I just want to know what I'm doing wrong?

Cheers every1
JoE
we are all of us living in the gutter.
But some of us are looking at the stars.
 
According to the Serializable API:

"Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:


private void writeObject(java.io_ObjectOutputStream out)
throws IOException
private void readObject(java.io_ObjectInputStream in)
throws IOException, ClassNotFoundException;"

I think that because some of your class variables are primitives (int, double) instead of objects, it cannot be serialized. Create the above methods and in them wrap your primitives in wrapper classes (Integer, Double), and then write them out/read them back manually to the ObjectOutput and InputStreams.

Alternately, you might try just rewriting the class so it has no class-level primitives. The default Serialization may then work...
 
thanks idarke, Ill try it in a sec.
Just wonderin' tho; is "out" and "in" simply the placeholders for my instances of ObjectOutputStream and ObjectInputStream? i.e. out = put
Cheers for all the help!
we are all of us living in the gutter.
But some of us are looking at the stars.
 
You pass your "put" into writeObject or readObject, just like you pass aClient into writeIt.

Just something else to think about -
While currently you are only calling
Code:
writeIt (Client aClient)
once, if you uncomment the do..while loop you will obviously be calling it as many times as there are Clients to enter.

Each time writeIt is called you are creating a new object, so if you enter in 10 clients, you create and then destroy and then create again 10 ObjectOutputStreams.
By far and away the most expensive process in Java is object creation, an hint to improve code performance would be to create the ObjectOutputStream just once (perhaps just below where you have created the BufferedReader
Code:
input

Your code is of course your own, but it may help your assignment score (or it may not - who knows with lecturers now a days). ----------------------------------------
There are no onions, only magic
----------------------------------------
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top