java实现文件上传下载功能

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class FileUploadDownloadExample {
// 服务器监听端口
private static final int PORT = 8888;
// 文件存储目录
private static final String FILE_DIR = “files/”;

public static void main(String[] args) {
    // 创建文件存储目录
    File dir = new File(FILE_DIR);
    if (!dir.exists()) {
        dir.mkdirs();
    }

    // 启动服务器线程
    new Thread(FileUploadDownloadExample::startServer).start();

    // 客户端功能选择
    Scanner scanner = new Scanner(System.in);
    while (true) {
        System.out.println("请选择操作:");
        System.out.println("1. 上传文件");
        System.out.println("2. 下载文件");
        System.out.println("3. 退出");
        int choice = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        switch (choice) {
            case 1:
                System.out.println("请输入要上传的文件路径:");
                String uploadFilePath = scanner.nextLine();
                uploadFile(uploadFilePath);
                break;
            case 2:
                System.out.println("请输入要下载的文件名:");
                String downloadFileName = scanner.nextLine();
                downloadFile(downloadFileName);
                break;
            case 3:
                System.out.println("退出程序");
                System.exit(0);
            default:
                System.out.println("无效选择,请重新输入");
        }
    }
}

// 启动服务器,处理文件上传和下载请求
private static void startServer() {
    try (ServerSocket serverSocket = new ServerSocket(PORT)) {
        System.out.println("服务器已启动,监听端口:" + PORT);

        while (true) {
            Socket clientSocket = serverSocket.accept();
            System.out.println("客户端连接:" + clientSocket.getInetAddress());

            // 为每个客户端创建一个线程处理请求
            new Thread(() -> handleClient(clientSocket)).start();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// 处理客户端请求
private static void handleClient(Socket clientSocket) {
    try (ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
         ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())) {

        // 读取请求类型
        String requestType = ois.readUTF();

        if ("upload".equals(requestType)) {
            // 处理文件上传
            handleFileUpload(ois);
            oos.writeUTF("上传成功");
        } else if ("download".equals(requestType)) {
            // 处理文件下载
            String fileName = ois.readUTF();
            boolean fileExists = handleFileDownload(fileName, oos);
            if (fileExists) {
                oos.writeUTF("下载成功");
            } else {
                oos.writeUTF("文件不存在");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// 处理文件上传
private static void handleFileUpload(ObjectInputStream ois) throws IOException {
    // 读取文件名
    String fileName = ois.readUTF();
    // 创建文件输出流
    try (FileOutputStream fos = new FileOutputStream(FILE_DIR + fileName)) {
        // 读取文件内容
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = ois.read(buffer)) != -1) {
            fos.write(buffer, 0, bytesRead);
        }
    }
    System.out.println("文件上传成功:" + fileName);
}

// 处理文件下载
private static boolean handleFileDownload(String fileName, ObjectOutputStream oos) throws IOException {
    File file = new File(FILE_DIR + fileName);
    if (!file.exists()) {
        return false;
    }

    // 发送文件名
    oos.writeUTF(fileName);

    // 发送文件内容
    try (FileInputStream fis = new FileInputStream(file)) {
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            oos.write(buffer, 0, bytesRead);
        }
    }
    System.out.println("文件下载成功:" + fileName);
    return true;
}

// 客户端上传文件
private static void uploadFile(String filePath) {
    File file = new File(filePath);
    if (!file.exists()) {
        System.out.println("文件不存在:" + filePath);
        return;
    }

    try (Socket socket = new Socket("localhost", PORT);
         ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
         ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
         FileInputStream fis = new FileInputStream(file)) {

        // 发送上传请求
        oos.writeUTF("upload");
        oos.flush();

        // 发送文件名
        oos.writeUTF(file.getName());
        oos.flush();

        // 发送文件内容
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            oos.write(buffer, 0, bytesRead);
        }
        oos.flush();

        // 接收服务器响应
        System.out.println(ois.readUTF());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// 客户端下载文件
private static void downloadFile(String fileName) {
    try (Socket socket = new Socket("localhost", PORT);
         ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
         ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {

        // 发送下载请求
        oos.writeUTF("download");
        oos.flush();

        // 发送文件名
        oos.writeUTF(fileName);
        oos.flush();

        // 接收服务器响应
        String response = ois.readUTF();
        if ("文件不存在".equals(response)) {
            System.out.println(response);
            return;
        }

        // 创建文件输出流
        try (FileOutputStream fos = new FileOutputStream("downloads/" + fileName)) {
            // 创建下载目录
            File dir = new File("downloads/");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 接收文件内容
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = ois.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        }

        System.out.println("文件下载成功:" + fileName);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值