• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Using an output stream to write an int to file

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm trying to create random numbers(which is working fine) but I need to get them to output to a file to be read later on.



Thats what I'm trying to do now, but nothing is getting put into the text file. Obviously I'm doing something wrong so any help would be appreciated. Thanks.
 
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When APIs don't work as you expect, always look them up in the JavaDocs as your first line of defense.

public void write(int c) throws IOException

Write a single character.

[And from Writer.write(int):

The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.

So it's treating the lower 16 bits of yuor random integer as a Unicode character and writing that. It may be that it can tell the character is invalid; who knows?

The main description for BufferedWriter has a good suggestion: wrap it in a PrintWriter:Now you can use println(int) to write each integer on a line. This writes them as text rather than the bytes as they are stored in memory. If you want to write them as raw bytes (non-human-readable) then use a DataOutputStream wrapped around a FileOutputSteram (BufferedOutputStream inbetween to mirror what you have).

The JavaDocs are your friend. Get to know them well.
 
I child proofed my house but they still get in. Distract them with this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic