[2706] in java-interest
Re: Dealing with byte[]s
daemon@ATHENA.MIT.EDU (Thomas Ball)
Wed Oct 11 08:20:31 1995
Date: Tue, 10 Oct 1995 19:45:38 -0700
From: Thomas.Ball@Eng.Sun.COM (Thomas Ball)
To: mikea@ai.mit.edu
Cc: java-interest@java.Eng.Sun.COM
> Where do bytes fit into the general Java scheme of things?
> They're not even defined under java.lang. Where did their need come
> from?
Network and other streams use bytes, and have no notion of other data
types. For low-level code, Java therefore needs to use them as well.
Also, Java's char type isn't the 8-bit entity that C's is, so the C
habit of using char arrays needs to be replaced with byte arrays.
(or break the habit :-)
> Basically, I have two very related problems:
>
> I'm reading some info from a InputStream and want to treat the
> info as a String. How can I convert one to the other?
Use a DataInputStream, which supports reading typed input. If you are
reading a text file, you'll want to use DataInputStream's readLine method.
For passing Strings back and forth (say, over a socket connection), use
the readUTF method on the input side and DataOutputStream's writeUTF
method on the output side.
> Furthermore, if for testing purposes I wish to explicitly
> create an array of bytes, what is the syntax? I declare it at the top
> of my program. How do I allocate memory for it? (I assume: line =
> new byte[123].)
byte line[] = new byte[123];
> More importantly, how do I specify its contents?
Bytes are just 8-bit integers, so you can initialize them with integers
less than 256:
for (int i = 0; i < 123; i++) {
line[i] = (byte)(Math.round(Math.random() * 255) % 255);
}
All of the input stream classes support reading into an array of bytes,
so that's another way of initializing that array. Finally, you can use
the String class's getBytes method, to copy a String into an array of
bytes.
Tom Ball
Java Products Group
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com