aspose file tools*
The moose likes Beginning Java and the fly likes Trouble writing an Integer to a text file and reading back with scanner and storing it. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Trouble writing an Integer to a text file and reading back with scanner and storing it. " Watch "Trouble writing an Integer to a text file and reading back with scanner and storing it. " New topic
Author

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

Jamal Taylor
Greenhorn

Joined: Sep 06, 2012
Posts: 20
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

Joined: Aug 16, 2005
Posts: 14269
    
  21

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

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Trouble writing an Integer to a text file and reading back with scanner and storing it.