要實現Java的離線文件傳輸,可以使用Socket編程來實現。下面是一個簡單的離線文件傳輸的示例代碼:
服務端代碼:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("等待客戶端連接...");
Socket socket = serverSocket.accept();
System.out.println("客戶端已連接");
// 接收文件
InputStream in = socket.getInputStream();
FileOutputStream out = new FileOutputStream("file.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
System.out.println("文件接收完成");
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客戶端代碼:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
// 發送文件
File file = new File("file.txt");
FileInputStream in = new FileInputStream(file);
OutputStream out = socket.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
System.out.println("文件發送完成");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上代碼中,服務端通過ServerSocket
監聽指定的端口,客戶端通過Socket
連接到服務端。客戶端將文件讀取為字節流,通過Socket
的輸出流發送給服務端,服務端接收數據并寫入文件。