title: File transfer through Socket in java
body: <p>I'm making a Network File Transfer System for transfering any kind of file over a network in java. The size also could be of any kind. Therefore I've used UTF-8 protocol for the task. </p>
  
  <p>I'm providing the codes which I've made but the problem is some times the file gets transfered as it is, with no problem at all. But sometimes few kb's of data is just skipped at the receiving end, which actually restricts the mp3/video/image file to be opened correctly. I think the problem is with BUFFER. I'm not creating any buffer which, right now, I think may be of some use to me.</p>
  
  <p>I would really appreciate if anyone could provide any help regarding the problem, so that the file gets transferred fully.</p>
  
  <p><strong>Client side :  --->>  File Sender</strong></p>
  
  <pre><code>Socket clientsocket = new Socket(host,6789);                        // host contains the ip address of the remote server
  DataOutputStream outtoserver = new DataOutputStream(clientsocket.getOutputStream());
  try
  {
      int r=0;
      FileInputStream fromFile1 = new FileInputStream(path);                  // "path" is the of the file being sent.
      while(r!=-1)
      {   
           r = fromFile1.read();
           outtoserver.writeUTF(r+"");
      }
  }
  catch(Exception e)
  {
      System.out.println(e.toString());
  }
  clientsocket.close();
  </code></pre>
  
  <p><strong>Server side:   --->>  File Receiver</strong></p>
  
  <pre><code>ServerSocket welcome = new ServerSocket(6789);
  Socket conn = welcome.accept();
  try
  {
      String r1 = new String();
      int r=0;
      FileOutputStream toFile1 = new FileOutputStream(path);                  // "path" is the of the file being received.
      BufferedOutputStream toFile= new BufferedOutputStream(toFile1);
      DataInputStream recv = new DataInputStream(conn.getInputStream());
      while(r!=-1)
      {   
          r1 = recv.readUTF();
          r = Integer.parseInt(r1);
          toFile.write(r);
      }
  }
  catch(Exception e)
  {
      System.out.println(e.toString());
  }
  </code></pre>