Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 21st, 2012  |  syntax: None  |  size: 1.40 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. when transferring files they get corrupted with java sockets
  2. DataInputStream input;
  3. DataOutputStream ouput;
  4. //these two variable are initialized somewhere else in the code.
  5. private void downloadFile() {
  6.     try {
  7.         String fileName= input.readUTF();
  8.         File f = new File(path + fileName);
  9.         size= f.length();
  10.         file= new FileInputStream(path+ fileName);
  11.         ouput.writeLong(size);
  12.         byte[] buffer = new byte[1024];
  13.         int len;
  14.         while ((len = file.read(buffer)) > 0) {
  15.             output.write(buffer, 0, len);
  16.         }
  17.     } catch (IOException e) {
  18.         e.printStackTrace();
  19.     }
  20. }
  21.        
  22. public void downloadFile(String fileName) {
  23.     try {
  24.         this.client= new Socket(ip,port);
  25.         DataInputStream input= new DataInputStream(this.client.getInputStream());
  26.         DataOutputStream ouput= new DataOutputStream(this.client.getOutputStream());
  27.  
  28.         output.writeUTF("DOWNLOAD");
  29.         output.writeUTF(fileName);
  30.  
  31.         File f = new File(path+ fileName);
  32.         file = new FileOutputStream(f);
  33.         byte[] buffer = new byte[1024];
  34.         int len;
  35.         while ((len = input.read(buffer)) > 0) {
  36.             file.write(buffer, 0, len);
  37.         }
  38.         file.flush();
  39.         file.close();
  40.         this.client.close();
  41.     } catch (Exception e) {
  42.         System.out.println("something went wrong");
  43.     }
  44. }
  45.        
  46. ouput.writeLong(size);
  47.        
  48. ouput.writeLong(size);