Java程序将一台服务器的文件夹内容传递到另外一台服务器,请提供相关demo
时间: 2024-03-10 19:48:55 浏览: 98
好的,以下是一个简单的 Java 程序,用于将一台服务器的文件夹内容传递到另外一台服务器:
```java
import java.io.*;
import java.net.*;
public class FileTransferDemo {
public static void main(String[] args) {
String sourceHost = "source.host.com";
String sourceFolder = "/path/to/source/folder";
String destinationHost = "destination.host.com";
String destinationFolder = "/path/to/destination/folder";
try {
// Connect to the source server
Socket sourceSocket = new Socket(sourceHost, 8888);
BufferedInputStream sourceStream = new BufferedInputStream(sourceSocket.getInputStream());
// Connect to the destination server
Socket destinationSocket = new Socket(destinationHost, 8888);
BufferedOutputStream destinationStream = new BufferedOutputStream(destinationSocket.getOutputStream());
// Send the source folder path to the source server
PrintWriter sourceWriter = new PrintWriter(sourceSocket.getOutputStream(), true);
sourceWriter.println(sourceFolder);
// Receive the file list from the source server
BufferedReader fileListReader = new BufferedReader(new InputStreamReader(sourceStream));
String fileList = fileListReader.readLine();
// Send the file list to the destination server
PrintWriter fileListWriter = new PrintWriter(destinationStream, true);
fileListWriter.println(fileList);
// Loop through the files in the source folder and transfer them to the destination server
String[] files = fileList.split(",");
for (String file : files) {
String filePath = sourceFolder + "/" + file;
FileInputStream fileStream = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileStream.read(buffer)) != -1) {
destinationStream.write(buffer, 0, bytesRead);
}
fileStream.close();
}
// Clean up
fileListWriter.close();
fileListReader.close();
sourceWriter.close();
sourceStream.close();
sourceSocket.close();
destinationStream.close();
destinationSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个程序假设源服务器和目标服务器都运行在端口 8888 上,并且使用 TCP 协议进行通信。在程序中,我们首先连接到源服务器和目标服务器,然后向源服务器发送源文件夹路径并接收文件列表。接下来,我们将文件列表发送到目标服务器,并循环遍历源文件夹中的每个文件,将它们传输到目标服务器。最后,我们清理所有连接和流。
请注意,此示例程序仅用于演示目的。实际应用中,您需要考虑更多的边缘情况和错误处理。
阅读全文