使用Java语言,编写使用TCP网络通信程序,实现将客户端的“C:\\1.jpg”文件上传至服务器端的硬盘“D:\\upload”中
时间: 2023-07-21 08:23:25 浏览: 132
src.rar_java Tcp
好的,我可以为您提供Java代码示例,实现客户端将文件上传至服务器的功能。请注意,这个代码示例只是一个基本的上传文件的示例,您需要对其进行修改以适应您的具体需求。
客户端代码:
```java
import java.io.*;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) {
Socket socket = null;
FileInputStream in = null;
OutputStream out = null;
try {
socket = new Socket("服务器IP地址", 8888);
System.out.println("连接成功!");
// 读取本地文件
File file = new File("C:\\1.jpg");
in = new FileInputStream(file);
// 发送文件名和文件长度
out = socket.getOutputStream();
String fileName = file.getName();
long fileLength = file.length();
out.write((fileName + "\n").getBytes());
out.write((fileLength + "\n").getBytes());
// 发送文件内容
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
System.out.println("文件发送完成!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
in.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
服务器端代码:
```java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
InputStream in = null;
FileOutputStream out = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接!");
// 接收文件名和文件长度
in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String fileName = reader.readLine();
long fileLength = Long.parseLong(reader.readLine());
System.out.println("接收到文件:" + fileName + ",文件大小为:" + fileLength + "字节");
// 保存文件到本地
File file = new File("D:\\upload\\" + fileName);
out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
System.out.println("文件保存完成!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
in.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
请将代码中的“服务器IP地址”替换为您服务器的实际IP地址,并将客户端要上传的文件路径替换为您的文件路径。
阅读全文