title: Transfering mp3 files over a TCP connection. Displaying the download progress using JProgressBar
body: <p>I am working on a program that sends an mp3 file over a TCP connection. I am trying to use a JProgressBar to show the download progress. However I don't know the file size before fully downloading it. Is there anyway I can get the file size before downloading it from the server side?</p>
  
  <p>Thanks in advance. Here is my code</p>
  
  <p>SERVER:</p>
  
  <pre><code>PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
  dataOut = new BufferedOutputStream(clientSocket.getOutputStream());
  file = new File(LIBRARY, data);
  //get length of file
  int fileLength = (int)file.length();
  
  fileData = new byte[fileLength];
  fileIn = new FileInputStream(file);
  BufferedInputStream bis = new BufferedInputStream(fileIn);
  bis.read(fileData, 0 , fileData.length);
  OutputStream os = clientSocket.getOutputStream();
  os.write(fileData, 0 , fileData.length);
  os.flush();
  clientSocket.close();
  </code></pre>
  
  <p>CLIENT:</p>
  
  <pre><code>int filesize=999999999; //A TEMPORARY FILE SIZE
  
  long start = System.currentTimeMillis();
  int bytesRead;
  int current = 0;
  // localhost for testing
  Socket sock = new Socket(SERVER_NAME,DEST_PORT);
  PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
  // receive file
  byte [] mybytearray  = new byte [filesize];
  out.println(request);
  InputStream is = sock.getInputStream();
  FileOutputStream fos = new FileOutputStream(request);
  BufferedOutputStream bos = new BufferedOutputStream(fos);
  bytesRead = is.read(mybytearray,0,mybytearray.length);
  current = bytesRead;
  System.out.println(bytesRead);
  
  do {
        bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
        if(bytesRead &gt;= 0) current += bytesRead;
  } while(bytesRead &gt; -1);
  
  bos.write(mybytearray, 0 , current);
  bos.flush();
  long end = System.currentTimeMillis();
  System.out.println(current);
  bos.close();
  sock.close();
  </code></pre>