2016-04-24 7 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); 
      } 
     } 
    } 

問題は、私は、ファイルをチェックしても、それをexistance、あります私は開くことができないファイルを作成します(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

なぜですか? 2行目のコードは、まったく何も行いません。簡単に削除することができます。 – EJP

関連する問題