Kevik
Kevik

Reputation: 9351

how to read out a byte array before the file into OutputStream

i want to send the file size and one other integer, the tabelet serial number from and android tablet to a server running windows 7:

what is wrong with my client code and how to make the server accept the to different byte streams of data?

client code of android tablet

   try {

                byte[] bytes = new byte[(int) length];
                fis = new FileInputStream(file2);
                bis = new BufferedInputStream(fis);
                bos = new BufferedOutputStream(socket.getOutputStream());

                int count;

                // convert integer to byte
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                DataOutputStream dos = new DataOutputStream(baos);
                dos.writeInt(1992);
                byte[] preByte = baos.toByteArray();

                // the first byte that sends the tablet serial number and the size of the next file it is going to send
                bis.read(preByte);

                // the next sent is the file itself which is a database file
                while ((count = bis.read(bytes)) > 0) {
                    bos.write(bytes, 0, count);
                }

                fis.close();
                bis.close();
                fis = null;
                bis = null;
                socket.close();

server code that will receive the two files

        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);

        System.out.println("streams are setup from new thread\n");

        is = socket.getInputStream();
        bufferSize = socket.getReceiveBufferSize();

        buffer = new byte[bufferSize];

        while ((count = is.read(buffer)) > 0) {
            bos.write(buffer, 0, count);
        } // end while

        bos.flush();
        bos.close();
        is.close();

Upvotes: 0

Views: 946

Answers (3)

user207421
user207421

Reputation: 310909

You don't need the ByteArrayOutputStream at all. Just wrap a DataOutputStream around the BufferedOutputStream, and do all the writes via the DataOutputStream.

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136022

try this

dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
dos.writeLong(length);
dos.writeInt(1992);
for (int b; (b = bis.read()) != -1;) {
   dos.write(b);
}

...

dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
long length = dis.readLong();
int serialNumber = dis.readInt();
... read bytes

Upvotes: 1

Eyal Schneider
Eyal Schneider

Reputation: 22446

It seems that you are reading into preByte array instead of writing it to the output stream:

bis.read(preByte);

You probably meant:

bos.write(preByte);

Upvotes: 0

Related Questions