【问题标题】:Sending large files through socket android通过socket android发送大文件
【发布时间】:2021-07-09 03:40:13
【问题描述】:

我正在尝试通过套接字发送大约 2.3 GB 的大文件。 所以,当我创建字节数组new byte[fileLength] 时,我会收到内存不足的错误消息。 我的代码是

        fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);

        DataInputStream dis = new DataInputStream(bis);

        int fileLength = (int) file.length();

        OutputStream os = socket.getOutputStream();

        DataOutputStream dos = new DataOutputStream(os);

        mybytearray = new byte[fileLength];

        dis.readFully(mybytearray, 0, mybytearray.length);

        dos.writeUTF(file.getName());

        dos.writeLong(mybytearray.length);
        int i = 0;
        while (i<100) {
            dos.write(mybytearray, i*(mybytearray.length/100), mybytearray.length/100);
            final int c=i;
            Log.e("TAG", "REQ HANDLER: Completed: \"+c+\"%\"" );
            i++;

        }

        dos.flush();

如何通过socket发送和接收这种大文件

【问题讨论】:

    标签: java android sockets


    【解决方案1】:

    当然,您不能一次发送文件,因为它太大了。您需要将其逐个发送,例如:

        File file = new File("someFile");
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
    
        DataInputStream dis = new DataInputStream(bis);
        Socket socket;  //your socket
        OutputStream os = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
    
        dos.writeUTF(file.getName());
        dos.writeLong(file.length());
    
        byte[] mybytearray = new byte[4096];
        int read = dis.read(mybytearray);
        while (read != -1) {
            dos.write(mybytearray, 0, read);
            read = dis.read(mybytearray);
        }
        dos.flush();
    

    尚未针对上述代码运行测试,但您可以理解。

    【讨论】:

    • 不需要根据dis.read()的返回值有条件地调用不同版本的dos.write()。你可以改用这个:int read; while ((read = dis.read(mybytearray)) != -1) { dos.write(mybytearray, 0, read); }
    • 任何人都可以解释如何在客户端接收该文件。
    猜你喜欢
    • 2015-10-04
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2012-06-26
    相关资源
    最近更新 更多