在Java中可以使用Socket來實現服務器之間的文件拷貝。以下是一個簡單的示例代碼:
import java.io.*;
import java.net.Socket;
public class FileCopyClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("serverIpAddress", 1234);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = new FileOutputStream("destinationFilePath");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
socket.close();
System.out.println("File copied successfully");
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的代碼中,首先建立一個Socket連接到目標服務器,然后創建輸入流從服務器讀取文件內容,并創建輸出流將文件內容寫入目標文件。最后關閉流和連接,完成文件拷貝操作。
在服務器端也需要相應的代碼來處理文件傳輸,以下是一個簡單的服務器端代碼示例:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class FileCopyServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(1234);
Socket socket = serverSocket.accept();
InputStream inputStream = new FileInputStream("sourceFilePath");
OutputStream outputStream = socket.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
System.out.println("File copied successfully");
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的代碼中,首先創建一個ServerSocket監聽指定端口,然后等待客戶端連接。一旦有客戶端連接,就創建輸入流從源文件讀取內容,并創建輸出流將內容寫入到客戶端。最后關閉流、連接和ServerSocket,完成文件傳輸操作。
需要注意的是,以上代碼只是一個簡單的示例,實際應用中可能還需要考慮文件大小、傳輸速度、網絡穩定性等因素。