josephus
josephus

Reputation: 8304

Sending Large file over network/localhost

Here's the code:

private void sendFile(InputStream file, OutputStream out) throws IOException {
        Log.d(TAG, "trying to send file...");
        final int buffer_size = 4096;
        try {
            byte[] bytes = new byte[buffer_size];
            while(true) {
                int count = file.read(bytes, 0, buffer_size);
                if (count == -1) {                  
                    break;
                }
                out.write(bytes, 0, count);
                Log.d("copystream", bytes + "");
            }
        } catch (Exception e) {
            Log.e("copystream", "exception caught while sending file... " + e.getMessage());
        }
    }

I'm trying to send a large File (InputStream file) over an output stream (OutputStream out). This code works for smaller files, but for something like 5mb and above (I haven't benchmarked the limit), it just freezes after sometime without error or anything.

Log.d("copystream", bytes + ""); would output for some time, but will eventually stop logging.

Log.e("copystream", "exception caught while sending file... " + e.getMessage()); never shows.

This is part of a larger codebase which is actually a file server that runs on the Android device.

Any ideas?

Upvotes: 1

Views: 1304

Answers (3)

josephus
josephus

Reputation: 8304

Here's what made it work:

while (true) {
  synchronized (buffer) {
    int amountRead = file.read(buffer);
    if (amountRead == -1) {
      break;
    }
    out.write(buffer, 0, amountRead);
  }
}

Upvotes: 1

Mayur Patil
Mayur Patil

Reputation: 50

Use AsyncTask Class for this, here is link for example http://developer.android.com/reference/android/os/AsyncTask.html

Upvotes: 0

Vikram Bodicherla
Vikram Bodicherla

Reputation: 7123

Use Multipart POST. Something like

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,null); 
entity.addPart("File", new FileBody (new File(FILE_PATH), MIME_TYPE));
httppost.setEntity(entity); 
HttpResponse response = httpclient.execute(httppost); 
return response;

Upvotes: 0

Related Questions