• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Trouble writing an Integer to a text file and reading back with scanner and storing it.

 
Jamal Taylor
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it at all possible,to convert my number to a string and insert it in the file. After that read it back in as a String and convert it as a integer, so then I can treat it as number. I have tried this using the scanner method and it throws me an exception. Please respond back.
this is what I thought of:


Thanks
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15482
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, ofcourse it's possible, and: when you get an exception, please tell us exactly what the exception is and where it occurs - that's valuable information that helps to identify what the cause of the problem is.

There are some problems with the code you posted.

First of all, why are you creating both a FileWriter (line 2) and a FileOutputStream / DataOutputStream (lines 3 and 4) for the file?

An important thing to understand is that Java has two kinds of I/O classes. There are Readers and Writers (the first kind) and InputStreams and OutputStreams (the second kind). Readers and writers are for reading and writing text files. Streams are for reading and writing binary files. Your code is mixing the two up; you're creating a FileWriter but you're not even using it.

DataOutputStream is a special kind of OutputStream that writes data in a specific binary format.

Scanner is for reading text. You can't use it to read binary data.

You're also not closing the writer or stream after writing to it.

Start by deleting lines 3, 4 and 5. Use the FileWriter to write to the file instead. Call wf.close(); after you're done writing to the file.

This part of Oracle's tutorials is about reading and writing text files: Character Streams
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic