如何将文件前的字节数组读出到OutputStream中

时间:2013-09-19 04:40:43

标签: java android sockets networking tcp

我想将文件大小和另一个整数,来自Android平板电脑的小册子序列号发送到运行Windows 7的服务器:

我的客户端代码有什么问题,以及如何让服务器接受不同的字节数据流?

Android平板电脑的客户端代码

   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();

将收到两个文件的服务器代码

        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();

3 个答案:

答案 0 :(得分:1)

试试这个

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

答案 1 :(得分:0)

您似乎正在读取preByte数组,而不是将其写入输出流:

bis.read(preByte);

你可能意味着:

bos.write(preByte);

答案 2 :(得分:0)

根本不需要ByteArrayOutputStream。只需在DataOutputStream周围打BufferedOutputStream,,然后通过DataOutputStream执行所有写操作。