您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,可以使用Socket和ServerSocket类来实现文件传输。以下是一个简单的示例,展示了如何使用这些类进行文件传输。
import java.io.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) {
int port = 12345;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server is listening on port " + port);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected");
InputStream inputStream = socket.getInputStream();
DataInputStream dataInputStream = new DataInputStream(inputStream);
// Read file name and size from client
String fileName = dataInputStream.readUTF();
long fileSize = dataInputStream.readLong();
// Write file to disk
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
byte[] buffer = new byte[4096];
int bytesRead;
long totalBytesRead = 0;
while (totalBytesRead < fileSize && (bytesRead = dataInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
}
fileOutputStream.close();
dataInputStream.close();
socket.close();
System.out.println("File received: " + fileName);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) {
String serverAddress = "localhost";
int port = 12345;
String filePath = "example.txt";
try (Socket socket = new Socket(serverAddress, port)) {
OutputStream outputStream = socket.getOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
// Send file name and size to server
File file = new File(filePath);
dataOutputStream.writeUTF(file.getName());
dataOutputStream.writeLong(file.length());
// Read file and send to server
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
dataOutputStream.write(buffer, 0, bytesRead);
}
fileInputStream.close();
dataOutputStream.close();
socket.close();
System.out.println("File sent: " + filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
这样,客户端会将指定的文件发送到服务器,服务器接收到文件后将其保存到本地。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。