Java 客户端向服务端上传mp3文件
时间: 2023-10-22 22:06:36 浏览: 94
在Java中,你可以使用Socket来实现客户端向服务端上传mp3文件的功能。下面是一个简单的示例代码:
客户端代码:
```java
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("服务器地址", 12345); // 替换为实际的服务器地址和端口号
File file = new File("文件路径"); // 替换为实际的mp3文件路径
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
dataOutputStream.write(buffer, 0, bytesRead);
}
dataOutputStream.flush();
dataOutputStream.close();
bufferedInputStream.close();
socket.close();
System.out.println("文件上传完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
服务端代码:
```java
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(12345); // 替换为实际的监听端口号
System.out.println("等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端连接成功");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("保存文件路径")); // 替换为实际的保存文件路径
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = socket.getInputStream().read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, bytesRead);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
socket.close();
serverSocket.close();
System.out.println("文件保存成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意替换代码中的服务器地址、端口号、文件路径和保存文件路径为实际的值。这个示例代码只是一个简单的演示,实际应用中可能需要进行错误处理、优化和安全性验证等。
阅读全文