title: Android Java TCP Client Server File Transfer
body: <p>Edit*
  I have successful on the client server. Now I am doing a file transferring between 2 emulators. The file did transfer between the emulators, but I notice that the file size received is not the same as the original file. For example, A.jpg size is 900KB, but the received file is less than 900KB. I checked the file transfer size, found that there were some data(byte) lost when transferring. How is this happening?</p>
  
  <p>Here's the code:</p>
  
  <p>Client (Send File)</p>
  
  <pre><code>File myFile = new File ("/mnt/sdcard/Pictures/A.jpg");
  FileInputStream fis = new FileInputStream(myFile);
  OutputStream os = socket.getOutputStream();
  int filesize = (int) myFile.length();
  
  byte [] buffer  = new byte [filesize];
       int bytesRead =0;
       while ((bytesRead = fis.read(buffer)) &gt; 0) {
       os.write(buffer, 0, bytesRead);
  //Log display exact the file size
       System.out.println("SO sendFile" + bytesRead);
       }
       os.flush();
       os.close();
       fis.close();
       Log.d("Client", "Client sent message");
       socket.close();
  </code></pre>
  
  <p>Server (Receive File)</p>
  
  <pre><code>FileOutputStream fos = new FileOutputStream("/mnt/sdcard/Pictures/B.jpg");
  @SuppressWarnings("resource")
  BufferedOutputStream bos = new BufferedOutputStream(fos);
  InputStream is = clientSocket.getInputStream();
  
  byte[] aByte = new byte[1024];
  int bytesRead;
  while ((bytesRead = is.read(aByte)) != -1) 
  {
       bos.write(aByte, 0, bytesRead);
  //Log display few parts the file size is less than 1024. I total up, the lost size caused the file received is incomplete
       System.out.println("SO sendFile" + bytesRead);
   }
  clientSocket.close();
  </code></pre>
  
  <p>*Edit 2</p>
  
  <p>While I surfed around google, I found that .read(buffer) does not guarantee read the full size(byte) of the file. Hence, the received file always lost some bytes (like space, empty character). To solve this, send the file size first to inform the receiver, then only start transfer the file.</p>