how to convert string to byte[]?

B

beruno

Is there a way of casting a String to a byte[]?
my objective is to write that string to a file using the method
FileOutputStream.write(byte[] arrayofbytes) and i get an inconvertible
types when i cast from String data to (byte[]) data.
thanks
 
T

Thomas Weidenfeller

Is there a way of casting a String to a byte[]?
my objective is to write that string to a file using the method
FileOutputStream.write(byte[] arrayofbytes) and i get an inconvertible
types when i cast from String data to (byte[]) data.
thanks

The correct way to write text data to a file is to use a Writer, not an
OutputStream.

But if you really want to mangle your text data pretty hard, read the
documentation of the String class.

/Thomas
 
G

Gordon Beaton

Is there a way of casting a String to a byte[]?
my objective is to
write that string to a file using the method
FileOutputStream.write(byte[] arrayofbytes) and i get an
inconvertible types when i cast from String data to (byte[]) data.

Casting cannot be used to change an object from one type to another.

However if you had spent a few moments browsing the API docs for
String, you would have found methods that do what you need.

Note too that any kind of Writer (such as an OutputStreamWriter or a
FileWriter) let you write Strings directly, i.e. they do the
conversion on the fly, so you don't have to.

/gordon
 
C

Chris Uppal

Is there a way of casting a String to a byte[]?
my objective is to write that string to a file using the method
FileOutputStream.write(byte[] arrayofbytes) and i get an inconvertible
types when i cast from String data to (byte[]) data.

Which bytes ?

Any given String has many different representations as binary data depending on
which character encoding you want to use. You /cannot/ convert a String to a
byte[] array without choosing an encoding. There are some APIs which /appear/
to allow you to do so (as you would have seen if you'd looked at the
documentation) but in fact they just choose the "system default" encoding for
you -- which is quite likely to be wrong for your purposes.

-- chris
 
R

Roedy Green

Is there a way of casting a String to a byte[]?
my objective is to write that string to a file using the method
FileOutputStream.write(byte[] arrayofbytes) and i get an inconvertible
types when i cast from String data to (byte[]) data.

A PrintWriter will do that conversion fro you automatically. See
http://mindprod.com/applets/fileio.html

And tell it you want to write encoded characters. It will generate
you a sample program.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top