This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes I/O and Streams and the fly likes How to convert from stream to byte array? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "How to convert from stream to byte array?" Watch "How to convert from stream to byte array?" New topic
Author

How to convert from stream to byte array?

gavin goh
Greenhorn

Joined: May 10, 2009
Posts: 6
private byte[] GetStreamAsByteArray (System.IO.Stream stream)
{
int streamLength = Convert.ToInt32(stream.length);
byte[] fileData = new byte[streamLength + 1];

stream.Read(fileData, 0, streamLength);
stream.Close();

return fileData;
}

This is what i found on the internet, but it can't seem to work.
Experts out there please help me.
My project deadline is in less than a week
Thanks !
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18757
    
  40

Maybe it would help to ask this question in a C# forum? ... I am assuming that you do know that this isn't Java code.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19679
    
  18

In Java you'd use a ByteArrayOutputStream to write to, then call its toByteArray() method. There is no such equivalent in C# I noticed.

You could write to a StringWriter, then convert the string into a byte[] somehow. Or you could put each byte into a List<byte> (yes people, this is allowed in C# ), then convert that into a byte[].


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
gavin goh
Greenhorn

Joined: May 10, 2009
Posts: 6
My apologies to all, i'm doing this on C# not on java. My bad !
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to convert from stream to byte array?