smie
smie

Reputation: 612

Save InputStream to ByteArray

My task is: Clients connect to ServerSocket and send files with any encoding what they want(UTF-8, ISO-8859-5, CP1251 e.g.). When Server receive file content, script must insert it into MySQL.

As the encoding can be different, I need save file content like ByteArray(?).

Byt I dont know how get ByteArray from Socket.getInputStream().

Please help with this.

Thanks in advance!

Upvotes: 2

Views: 5157

Answers (2)

Rocky Pulley
Rocky Pulley

Reputation: 23301

ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] tmp = new byte[4096];
int ret = 0;

while((ret = inputStream.read(tmp)) > 0)
{
    bos.write(tmp, 0, ret);
}

byte[] myArray = bos.toByteArray();

Upvotes: 4

Ondra Žižka
Ondra Žižka

Reputation: 46796

Commons IO - http://commons.apache.org/io/

toByteArray(Reader input, String encoding) Get the contents of a Reader as a byte[] using the specified character encoding.

http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html

Upvotes: 2

Related Questions