This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

problem outputting to file  RSS feed

 
joew weakers
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there. I am relatively new to java and I am having some slight problems with the FileOutputStream and ObjectOutputStream classes. Basically what I am trying to do is output a double value to a text file using the above classes. However when I run my program it creates the output file but the contents are complete gibberish...they make no sense. can anyone make any suggestions as to where i may be going wrong. The following is the code from my program which creates and populates the output file:
protected static void printPoints(Vector ptv) throws Exception
{
Iterator it = ptv.iterator();
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream("C://db.txt")) ;

try
{
while(it.hasNext())
{
Point point = (Point) it.next();
double a = point.getX();
//System.out.println(a);
out.writeDouble(a);
double b = point.getY():
//System.out.println(b);
out.writeDouble(6.7936);

}
System.out.println(ptv);

}
catch (Exception e) {}
out.flush();
out.close();
}
When I print out variables a,b and ptv to the screen it returns just doubles. When I output to the file it returns absloute rubbish
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to actually read the file, then instead use a PrintWriter. You'll notice that it has overloaded print and println statements, one of which handles doubles.
Since you aren't actually writing an object, I wouldn't even think of using an ObjectOutputStream. That stream deals with things at the byte level, which gets translated to "gibberish" in a text file. Personally I don't why an Object stream would deal with primitives, but that's me.
So wrap your FileOutputStream in a PrintWriter, and you should be good!
 
joew weakers
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cheers jason. I actually came across that just after posting my query and it is now working very nicely. Cheers for getting back to me so promptly, Joe
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!