教育路上
摘要:java 实现 文件 上传 服务器端 和 客户端 ,实现文件上传服务器端和客户端,掌握文件上传的实现思路。以下是我们为大家整理的,相信大家阅读完后肯定有了自己的选择吧。
2022-05-12 21:26网络推荐
文件上传
任务介绍:实现文件上传服务器端和客户端
任务目标:掌握文件上传的实现思路
实现思路:文件上传客户端中将打开一个指定文件并从该文件中读取字节流到缓冲区 buffer
中,然后将缓冲区中的数据写入到网络流中。在文件上传服务器中,先从网络流中读取数据
到缓冲区,再将缓冲区数据写入到文件流中。
实现代码
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 10001); // 创建客户端 Socket
OutputStream out = socket.getOutputStream(); // 获取 Socket 的输出流对象
// 创建 FileInputStream 对象
FileInputStream fis = new FileInputStream("F:\\1.jpg");
byte[] buf = new byte[1024]; // 定义一个字节数组
int len; // 定义一个 int 类型的变量 len
while ((len = fis.read(buf)) != -1) { // 循环读取数据
out.write(buf, 0, len);
}
socket.shutdownOutput(); // 关闭客户端输出流
InputStream in = socket.getInputStream(); // 获取 Socket 的输入流对象
byte[] bufMsg = new byte[1024]; // 定义一个字节数组
int num = in.read(bufMsg); // 接收服务端的信息
String Msg = new String(bufMsg, 0, num);
System.out.println(Msg);
fis.close(); // 关键输入流对象
socket.close(); // 关闭 Socket 对象
}
}
import java.io.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(10001); // 创建 ServerSocket 对象
while (true) {
// 调用 accept()方法接收客户端请求,得到 Socket 对象
Socket s = serverSocket.accept();
// 每当和客户端建立 Socket 连接后,单独开启一个线程处理和客户端的交互
new Thread(new ServerThread(s)).start();
}
}
}
class ServerThread implements Runnable {
private Socket socket; // 持有一个 Socket 类型的属性
public ServerThread(Socket socket) { // 构造方法中把 Socket 对象作为实参传入
this.socket = socket;
}
public void run() {
String ip = socket.getInetAddress().getHostAddress(); // 获取客户端的 IP 地址
int count = 1; // 上传图片个数
try {
InputStream in = socket.getInputStream();
File parentFile = new File("F:\\upload\\"); // 创建上传图片目录的 File 对象
if (!parentFile.exists()) { // 如果不存在,就创建这个目录
parentFile.mkdir();
}
// 把客户端的 IP 地址作为上传文件的文件名
File file = new File(parentFile, ip + "(" + count + ").jpg");
while (file.exists()) {
// 如果文件名存在,则把 count++
file = new File(parentFile, ip + "(" + (count++) + ").jpg");
}
// 创建 FileOutputStream 对象
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024]; // 定义一个字节数组
int len = 0; // 定义一个 int 类型的变量 len,初始值为 0
while ((len = in.read(buf)) != -1) { // 循环读取数据
fos.write(buf, 0, len);
}
OutputStream out = socket.getOutputStream();// 获取服务端的输出流
out.write("上传成功".getBytes()); // 上传成功后向客户端写出“上传成功”
fos.close(); // 关闭输出流对象
socket.close(); // 关闭 Socket 对象
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
访客的评论 2023/12/07 07:46
文中描述的是准确的吗,如何报名!