2012-06-11 20 views
0

我想使我的服務器能夠獲取將被髮送到它的文件的名稱,然後獲得該文件後,它可以將它保存在新的位置與正確的名稱。發送文件的名稱然後文件本身

這裏是服務器代碼:

class TheServer { 

    public void setUp() throws IOException { // this method is called from Main class. 
     ServerSocket serverSocket = new ServerSocket(1991); 
     System.out.println("Server setup and listening..."); 
     Socket connection = serverSocket.accept(); 
     System.out.println("Client connect"); 
     System.out.println("Socket is closed = " + serverSocket.isClosed()); 



     BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); 

     String str = rd.readLine(); 
     System.out.println("Recieved: " + str); 
     rd.close(); 



     InputStream is = connection.getInputStream(); 

     int bufferSize = connection.getReceiveBufferSize(); 

     FileOutputStream fos = new FileOutputStream("C:/" + str); 
     BufferedOutputStream bos = new BufferedOutputStream(fos); 


     byte[] bytes = new byte[bufferSize]; 

     int count; 

     while ((count = is.read(bytes)) > 0) { 
      bos.write(bytes, 0, count); 
     } 

     bos.flush(); 
     bos.close(); 
     is.close(); 
     connection.close(); 
     serverSocket.close(); 


    } 
} 

這裏是客戶端代碼:

public class TheClient { 

    public void send(File file) throws UnknownHostException, IOException { // this method is called from Main class. 
     Socket socket = null; 
     String host = "127.0.0.1"; 

     socket = new Socket(host, 1991); 

     // Get the size of the file 
     long length = file.length(); 
     if (length > Integer.MAX_VALUE) { 
      System.out.println("File is too large."); 
     } 

     BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 
     wr.write(file.getName()); 
     wr.flush(); 

     byte[] bytes = new byte[(int) length]; 
     FileInputStream fis = new FileInputStream(file); 
     BufferedInputStream bis = new BufferedInputStream(fis); 
     BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream()); 

     int count; 

     while ((count = bis.read(bytes)) > 0) { 
      out.write(bytes, 0, count); 
     } 


     out.flush(); 
     out.close(); 
     fis.close(); 
     bis.close(); 
     socket.close(); 
    } 
} 

我做了我自己的一些測試,似乎我的客戶端發送的名字文件的權利,但不知何故服務器得到它的錯誤。例如,如果我的客戶端告訴文件的名稱是「test.txt」,我的服務器就會得到它,比如「test.txt' --------------------」或「test.txtPK」。我不明白爲什麼它沒有正常的名字。任何人都知道這是爲什麼發生?還是有更簡單的方法來做到這一點?而我的第二個問題是,我怎樣才能不僅在localhost而且在任何地方使用它?我試圖改變我的主機到我的IP地址,但它沒有奏效。謝謝。

回答

3

你永遠不會發送文件名後的行尾。因此,當服務器使用readLine()讀取時,它將讀取所有字符,直到它找到可能位於文件內容某處的第一行。有時是在'-----'之後,有時在'PK'之後。

+0

你能告訴我該怎麼做嗎? –

+0

只需在'wr.write(file.getName())'後面調用'wr.newLine()'。我自己,我可能會使用像Apache Commons IO這樣的庫。它在'java.io'類的基礎上有很多有用的工具。 –

+0

這很棒!謝謝 –

相關問題