简体   繁体   中英

Sending large files through socket android

I am trying to send large file about 2.3 GB through socket. So,When i create byte array new byte[fileLength] ,I will get the error that says out of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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