• Post Reply Bookmark Topic Watch Topic
  • New Topic

fileoutputstream question  RSS feed

 
Ryan Bishop
Ranch Hand
Posts: 143
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm working on a problem where I have to use the FileInputStream to opens a file that contains the name of a user's favorite book and then displays it.
If the file doesn't exist, then I prompt for the book title and write it to the file using FileOutputStream. This is what I have so far but I'm lost because
if I put a file that exists in line 8 then it closes, but if I don't and the user puts their favorite book nothing happens. Or, as far as I can tell
nothing does. Am I missing something?

 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use input streams for text files. I personally would use a Scanner for a text file, but if you want to use the older classes, use a buffered reader wrapped round a file reader.
I don't like the read() method; as you can see it is awkward at best. And you have method in Scanner and buffered reader which read the whole line.
Don't have if-else statements for reading the file depending on whether you know the name or not. That should be divided up into methods to read the file and methods to find the file name. Also methods for writing.
Output streams are not designed for text files. Use a file writer or print writer instead. You can use a buffered writer wrapped round a file writer, but I would prefer a Formatter. In both cases you can write a whole line at once with a single method call.
I suggest you go through the Java Tutorials sections. You will find lots more there than I have told you, and newer things too (NIO2).
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And you realise that you may never see the output if you forget to flush the stream, which is only necessary when writing. In most cases the close method flushes the stream before closing.
 
Piet Souris
Master Rancher
Posts: 2044
75
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Spot on (@Campbell).

I would like to mention one other thing:

If you manually input the book title, you use this title also as the name of your file.
(see line 27). So the file, with the booktitle in it, is saved somewhere (probably
your user directory), where you might not see it.

An easy way to check is to add line 32 and a half, something like

Greetz,
Piet
 
Ryan Bishop
Ranch Hand
Posts: 143
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help. I'm just putzing through this textbook I got for cheap and that's how the problem is worded. Just trying to learn on my own during free time. Thanks again.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!