Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

BufferedWriter and incorrect data...  RSS feed

 
Pat Peg
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I create a file with BufferWriter and use 'myFile.write(small);' where small is an int of value 20000. when I do a BufferedReader on the same file I read back 63. If I increment my writes the file output increments although at some point soon the actual file is containing single character values and is moving up the ascii table(so that if I go and check my actual output.txt file I see'?', 'A', 'B','C', etc.) I guess my question is a very simple, how do I write and read an int value in files?

Thanks
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The single argument write() takes a single character as an argument; if you pass an int, it's truncated to the low 16 bits and interpreted as a character, as you've observed. To write a human-readable number, you have to (one way or another) convert it to a human-readable String and print that String. One way to do it is with the PrintWriter class, which will format and print many kinds of numbers and other values automatically.



This will create a file containing the characters '2', '0', '0', '0', '0', followed by the end-of-line sequence for your platform.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!