Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

writing String data to a file

 
Senaca Boyd
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm familiar with writeInt, writeLong, etc., methods for writing primitive numerical data types to a file, but does Java provide a similar method for writing String data to a file?
 
Srikanth Ramu
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
to write string into a file you can use java.io.PrintStream
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends what you want. Which writeInt() etc. methods are you using - i.e. what class?

If we're talking about java.io.ObjectOutputStream class, you have two choices for writing String. You can use writeObject(), as a String is an Object. Or you can use writeUTF(), which writes the String more compactly and is specific to String data.

Note that, if you did want to write String to a text file, PrintWriter and FileWriter are usually preferred to PrintStream, because PrintStream has encoding issues (see its JavaDoc).
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
writeInt() and writeLong() could also be from a DataOutputStream or RandomAccessFile. In which case, use writeUTF().
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic