2013-08-19 33 views
1

我需要改变这个代码,以便它会在它目前只发送一个文件的时刻发送图像文件的目录的目录,我的主要目标是有它要求一个目录,然后送所有在该目录中的文件(图像文件)到服务器,然后我需要它来显示有多少数据被发送的代码,我现在拥有的是:如何发送文件

客户:

package sockets; 
import java.net.*; 
import java.io.*; 

public class Client { 

    public static void main (String [] args) throws IOException { 
     int filesize=1022386; 
     int bytesRead; 
     int currentTot = 0; 
     Socket socket = new Socket("127.0.0.1",6789); 
     byte [] bytearray = new byte [filesize]; 
     InputStream is = socket.getInputStream(); 
     FileOutputStream fos = new FileOutputStream("copy.txt"); 
     BufferedOutputStream bos = new BufferedOutputStream(fos); 
     bytesRead = is.read(bytearray,0,bytearray.length); 
     currentTot = bytesRead; 
     System.out.println("The Size of the data transferred is " + bytesRead + " Bytes"); 

     do { 
      bytesRead = 
       is.read(bytearray, currentTot, (bytearray.length-currentTot)); 
      if(bytesRead >= 0) currentTot += bytesRead; 
     } while(bytesRead > -1); 

     bos.write(bytearray, 0 , currentTot); 
     bos.flush(); 
     bos.close(); 
     socket.close(); 
     } 
} 

服务器:

package sockets; 
import java.net.*; 
import java.io.*; 
public class Server { 


public static void main (String [] args) throws IOException {` 

      ServerSocket serverSocket = new ServerSocket(6789); 
       Socket socket = serverSocket.accept(); 
       System.out.println("Accepted connection : " + socket); 
       File transferFile = new File ("Orders.txt"); 
       byte [] bytearray = new byte [(int)transferFile.length()]; 
       FileInputStream fin = new FileInputStream(transferFile); 
       BufferedInputStream bin = new BufferedInputStream(fin); 
       bin.read(bytearray,0,bytearray.length); 
       OutputStream os = socket.getOutputStream(); 
       System.out.println("Sending Files..."); 
       os.write(bytearray,0,bytearray.length); 
       os.flush(); 
       socket.close(); 
       System.out.println("File transfer complete"); 
      } 
} 

谢谢

回答

1

遍历所选目录中的所有文件,并得到所有你想要发送的已知的图像扩展。

Here's an example用于遍历文件。

然后,流从客户端中的每个这些文件的字节到你的服务器。

我建议使用FTP为您的文件发送到您的服务器作为其既定的协议正是这种类型的问题。

0

不可能完全按照原样发送目录。你有2个选项:

  1. 创建一个zip文件,并发送它。
  2. 打开目录并迭代整个目录并单独发送每个文件。
+0

如果我采取了第二个选项,您可以显示如何我将不得不迭代它的目录由于一段示例代码 – user2698097