java - 如何将文件之前的字节数组读入OutputStream

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

最佳答案

试试这个

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

关于java - 如何将文件之前的字节数组读入OutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18886316/

相关文章:

sockets - 检查 socket 是否仍然打开而没有阻塞

java - if 语句中的条件始终为 true

java - 无法获取 java 代码将用户输入的数据分配给 Joptionpane 中的对象字段

java - SQL Server Java 兼容 GUID/UUID(Big Endian 唯一标识符)

android - '安卓 :launchMode ="singleInstance"' does not allow activity for results update

android - 如何获取 SSLCertificateSocketFactory 实例?

java - 如何使用注释设置模型中列的默认值

Android自定义动画,如机场时间表

android - PhoneGap API 覆盖率与 native 覆盖率

java - 运算符(operator)控制台应用程序 - Java/Flex