2016-04-24 58 views
-1

我正在使簡單的客戶端 - 服務器應用程序在服務器上創建文件副本。FileOutputStream創建文件,即使我檢查文件存在

有發送文件到服務器的客戶方方法:

private void makeCopy(Socket clientSock) throws IOException { 
     File file = new File("D:\\client\\toCopy.bmp"); 
     File dest = new File("D:\\server\\copyFile.bmp"); 
     boolean ifExists = dest.exists(); 
     if(ifExists && !file.isDirectory()){ 
      System.out.println("Copy is already made on server."); 
     } 
     else{ 
      fis = new FileInputStream(file); 
      byte[] buffer = new byte[4096]; 
      while (fis.read(buffer) > 0) { 
       oos.write(buffer); 
      } 
      //fis.close(); 
      oos.close(); 
     } 

    } 

也有服務器端方法從客戶端接收文件:

public void saveFile(Socket s) throws IOException{ 

     File copy = new File("D:\\server\\fileCopy.bmp"); 
     fos = new FileOutputStream(copy); 
     File fromServer = new File("D:\\client\\toCopy.bmp"); 
     if(copy.exists() && !copy.isDirectory()){ 

     } 
     else{ 
      byte[] buffer = new byte[4096]; 

      int filesize = (int)fromServer.length(); 
      int read = 0; 
      int totalRead = 0; 
      int remaining = filesize; 
      while((read = ois.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) { 
       totalRead += read; 
       remaining -= read; 
       System.out.println("read " + totalRead + " bytes."); 
       fos.write(buffer, 0, read); 
      } 
     } 
    } 

的問題是,即使我檢查文件的實存它仍然生成我無法打開的文件(它有0個字節寫入)。有任何想法嗎 ?

+0

此代碼不會生成零長度文件,除非您發送零長度文件。一個客戶端如何可能用'File'類檢查服務器上的內容?你的問題沒有意義。注意您的客戶端複製循環不正確。這裏有很多正確的例子。 – EJP

回答

-1

FileOutputStream在文件系統中創建文件輸出流和文件。 首先你應該檢查存在,然後創建FileOutputStream。

File copy = new File("D:\\server\\fileCopy.bmp"); 
if(copy.exists() && !copy.isDirectory()){ } 
fos = new FileOutputStream(copy); 
File fromServer = new File("D:\\client\\toCopy.bmp"); 
+0

爲什麼?你的第二行代碼完全沒有。它可以簡單地刪除。 – EJP

相關問題