简体   繁体   English

通过socket android发送大文件

[英]Sending large files through socket android

I am trying to send large file about 2.3 GB through socket.我正在尝试通过套接字发送大约 2.3 GB 的大文件。 So,When i create byte array new byte[fileLength] ,I will get the error that says out of memory.所以,当我创建字节数组new byte[fileLength]时,我会得到 memory 的错误。 my code is我的代码是

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

How to can i send and receive this kind of large file through socket如何通过套接字发送和接收这种大文件

Of course, you can't send the file at once as it's too large.当然,您不能一次发送文件,因为它太大了。 You need to send it piece by piece like:您需要将其逐个发送,例如:

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

haven't run a test against the code above but you can get the idea.尚未对上面的代码进行测试,但您可以理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM