手记

Java 文件上传下载管理器(控制台)

文件上传下载管理器
项目技术

JDBC + IO + Socket

实现功能
  1. 客户端注册:通过输入用户名,密码,确认密码并且校验完成以后将用户信息储存在数据库中。
  2. 客户端登录:通过输入用户名和密码到数据库中校验,校验完成进入文件上传下载管理器。
  3. 上传文件:通过输入上传文件的路径上传到数据库,支持多个文件上传。
  4. 查看文件:通过登录的用户名查找上传的文件。
  5. 下载文件:通过输入文件的编号和下载的路径,从数据库进行下载。
  6. 删除文件:通过输入文件的编号进行单个文件的删除。

(ps:这次花了一天才写完,不过收获也很多,不足之处,多多交流)

完整代码
User.java
package com.xk;

import java.io.Serializable;

@SuppressWarnings("serial")
public class User implements Serializable {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}
FileEntity.java
package com.xk;

import java.io.Serializable;

@SuppressWarnings("serial")
public class FileEntity implements Serializable {
    private String username;
    private String fileName;
    private int id;
    private byte[] fileContent;

    public FileEntity(int id, String fileName) {
        this.id = id;
        this.fileName = fileName;
    }

    public FileEntity() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public byte[] getFileContent() {
        return fileContent;
    }

    public void setFileContent(byte[] fileContent) {
        this.fileContent = fileContent;
    }

    @Override
    public String toString() {
        return id + "\t" + fileName;
    }

}
CommandRelay.java
package com.xk;

import java.io.Serializable;
import java.util.ArrayList;

@SuppressWarnings("serial")
public class CommandRelay implements Serializable {
    private String command;
    private boolean flag;
    private Object userObject = null;
    private Object fileObject = null;
    private byte[] bytes = null;
    private ArrayList<FileEntity> fileList = null;

    public String getCommand() {
        return command;
    }

    public void setCommand(String command) {
        this.command = command;
    }

    public Object getUserObject() {
        return userObject;
    }

    public void setUserObject(Object userObject) {
        this.userObject = userObject;
    }

    public Object getFileObject() {
        return fileObject;
    }

    public void setFileObject(Object fileObject) {
        this.fileObject = fileObject;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public ArrayList<FileEntity> getFileList() {
        return fileList;
    }

    public void setFileList(ArrayList<FileEntity> fileList) {
        this.fileList = fileList;
    }

    public byte[] getBytes() {
        return bytes;
    }

    public void setBytes(byte[] bytes) {
        this.bytes = bytes;
    }

}
DBUtil.java
package com.xk;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/FileUpload";
    private static final String NAME = "root";
    private static final String PASSWORD = "root";

    /*
     * 数据库连接
     */
    public Connection getConnection() {
        try {
            Class.forName(DRIVER);
            Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD);
            return conn;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /*
     * 数据库关闭
     */
    public void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
DBTools.java
package com.xk;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class DBTools {
    DBUtil dbu = new DBUtil();
    Connection con = dbu.getConnection();

    /*
     * 用户登录
     */
    public boolean login(User user) throws Exception {
        String sql = "select * from users where username = ? and password = ?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1, user.getUsername());
        ps.setString(2, user.getPassword());
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * 用户注册
     */
    public boolean register(User user) {
        String sql = "insert into users(username,password) value(?,?)";
        try {
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /*
     * 上传文件
     */
    public boolean uploadFile(FileEntity fe) {
        String sql = "insert into file(username,filename,filecontent) VALUES(?,?,?)";
        try {
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, fe.getUsername());
            ps.setString(2, fe.getFileName());
            ps.setBytes(3, fe.getFileContent());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /*
     * 下载文件
     */
    public byte[] downloadFile(FileEntity fe) throws Exception {
        String sql = "select filecontent from file where id = ?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setInt(1, fe.getId());
        ResultSet rs = ps.executeQuery();
        InputStream is = null;
        if (rs.next()) {
            is = rs.getBinaryStream(1);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[is.available()];
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            return buffer;
        }
        return null;
    }

    /*
     * 查看文件
     */
    public ArrayList<FileEntity> viewFile(FileEntity fe) throws Exception {
        ArrayList<FileEntity> fileList = new ArrayList<>();
        String sql = "select id,filename from file where username= ? ";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1, fe.getUsername());
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            fileList.add(new FileEntity(rs.getInt(1), rs.getString(2)));
        }
        return fileList;
    }

    /*
     * 删除文件
     */
    public boolean deleteFile(FileEntity fe) throws Exception {
        String sql = "delete from file where id = ?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setInt(1, fe.getId());
        ps.execute();
        if (ps.getUpdateCount() > 0) {
            return true;
        }
        return false;
    }
}
Server.java
package com.xk;

import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main(String[] args) throws Exception {
        @SuppressWarnings("resource")
        ServerSocket ss = new ServerSocket(8722);
        Socket socket = null;
        System.out.println("服务器已经启动!");
        while (true) {
            socket = ss.accept();
            ServerThread st = new ServerThread(socket);
            st.start();
        }
    }

}
ServerThread.java
package com.xk;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

public class ServerThread extends Thread {
    Socket socket = null;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            CommandRelay cr = (CommandRelay) ois.readObject();
            try {
                cr = inquire(cr);
                oos.writeObject(cr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public CommandRelay inquire(CommandRelay cr) throws Exception {
        User user = (User) cr.getUserObject();
        FileEntity fe = (FileEntity) cr.getFileObject();
        DBTools dbt = new DBTools();
        boolean flag = false;
        switch (cr.getCommand()) {
        case "login":
            flag = dbt.login(user);
            break;
        case "register":
            flag = dbt.register(user);
            break;
        case "upload":
            flag = dbt.uploadFile(fe);
            break;
        case "view":
            ArrayList<FileEntity> fileList = dbt.viewFile(fe);
            if (!fileList.isEmpty()) {
                flag = true;
                cr.setFileList(fileList);
            }
            break;
        case "download":
            byte[] bytes = dbt.downloadFile(fe);
            if (bytes != null) {
                flag = true;
                cr.setBytes(bytes);
            }
            break;
        case "delete":
            flag = dbt.deleteFile(fe);
            break;
        default:
            break;
        }
        cr.setFlag(flag);
        return cr;
    }
}
Client.java
package com.xk;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;

public class Client {
    String username = null;
    String password = null;
    Socket socket = null;
    User user = new User();
    FileEntity fe = null;
    Scanner input = new Scanner(System.in);

    /*
     * 发送对象
     */
    public void sendData(CommandRelay cr) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        oos.writeObject(cr);
        oos.flush();
    }

    /*
     * 接收对象
     */
    public CommandRelay getData() throws Exception {
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        CommandRelay cr = (CommandRelay) ois.readObject();
        return cr;
    }

    /*
     * 用户登陆
     */
    public void login() throws Exception {
        System.out.println("*********开始登陆帐号***********");
        int count = 0;
        CommandRelay cr = new CommandRelay();
        while (true) {
            System.out.print("请输入帐号: ");
            username = input.next();
            user.setUsername(username);
            System.out.print("请输入密码: ");
            user.setPassword(input.next());
            count++;
            if (count == 3) {
                System.out.println("密码错误3次,退出系统!");
                System.exit(0);
            }
            cr.setCommand("login");
            cr.setUserObject(user);
            socket = new Socket("localhost", 8722);
            sendData(cr);
            cr = getData();
            if (cr.isFlag()) {
                break;
            } else {
                System.out.println("帐号或密码输入错误,请重新输入!");
                continue;
            }
        }
        System.out.println("登陆成功,进入文件上传下载器!");
        fileMain();
    }

    /*
     * 用户注册
     */
    public void register() throws Exception {
        System.out.println("**********开始注册帐号**********");
        String confirm = null;
        CommandRelay cr = new CommandRelay();
        while (true) {
            System.out.print("请输入帐号: ");
            username = input.next();
            System.out.print("请输入密码: ");
            password = input.next();
            System.out.print("请再次输入密码: ");
            confirm = input.next();
            if (!password.equals(confirm)) {
                System.out.println("两次密码不一致,请重新输入!");
                continue;
            }
            user.setUsername(username);
            user.setPassword(password);
            cr.setCommand("register");
            cr.setUserObject(user);
            socket = new Socket("localhost", 8722);
            sendData(cr);
            cr = getData();
            if (cr.isFlag()) {
                break;
            } else {
                System.out.println("注册失败,请重新注册!");
                continue;
            }
        }
        System.out.println("注册成功请登陆!");
        login();
    }

    /*
     * 文件上传下载界面
     */
    public void fileMain() throws Exception {
        System.out.println("********文件上传下载界面*********");
        System.out.print("1.上传\n2.下载\n3.查看\n4.删除\n5.退出\n请输入: ");
        String flag = null;
        while (true) {
            flag = input.next();
            switch (flag) {
            case "1":
                upload();
                break;
            case "2":
                download();
                break;
            case "3":
                view();
                break;
            case "4":
                delete();
                break;
            case "5":
                System.out.println("欢迎下次使用,再见!");
                System.exit(0);
                break;
            default:
                System.out.println("输入指令不正确,请重新输入");
                continue;
            }
            break;
        }
    }

    /*
     * 文件上传
     */
    @SuppressWarnings("resource")
    public void upload() throws Exception {
        System.out.println("***********上传文件************");
        System.out.println("请输入上传路径(如 D:/file/bear.jpg):");
        String path = input.next();
        String filename = path.substring(path.lastIndexOf('/') + 1);
        FileInputStream fis = new FileInputStream(path);
        byte[] fileBytes = new byte[fis.available()];
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(fileBytes);
        FileEntity fe = new FileEntity();
        fe.setUsername(username);
        fe.setFileName(filename);
        fe.setFileContent(fileBytes);
        CommandRelay cr = new CommandRelay();
        cr.setCommand("upload");
        cr.setFileObject(fe);
        socket = new Socket("localhost", 8722);
        sendData(cr);
        cr = getData();
        if (cr.isFlag()) {
            System.out.println("上传成功,返回主界面!");
            fileMain();
        } else {
            System.out.println("上传失败,请重新上传!");
        }
        close();
    }

    /*
     * 文件查看
     */
    public void view() throws Exception {
        System.out.println("***********查看文件************");
        FileEntity fe = new FileEntity();
        fe.setUsername(username);
        CommandRelay cr = new CommandRelay();
        cr.setCommand("view");
        cr.setFileObject(fe);
        socket = new Socket("localhost", 8722);
        sendData(cr);
        cr = getData();
        if (cr.isFlag()) {
            ArrayList<FileEntity> fileList = cr.getFileList();
            System.out.println("编号\t文件名");
            for (FileEntity fileEntity : fileList) {
                System.out.println(fileEntity);
            }
        } else {
            System.out.println("没有文件,还未上传文件!");
        }
        fileMain();
        close();
    }

    /*
     * 文件下载
     */
    @SuppressWarnings("resource")
    public void download() throws Exception {
        System.out.println("***********下载文件************");
        System.out.print("请输入要下载文件的编号:");
        FileEntity fe = new FileEntity();
        fe.setId(input.nextInt());
        System.out.println("请输入下载路径(如 D:/file/bear.jpg):");
        String filename = input.next();
        CommandRelay cr = new CommandRelay();
        cr.setCommand("download");
        cr.setFileObject(fe);
        socket = new Socket("localhost", 8722);
        sendData(cr);
        cr = getData();
        if (cr.isFlag()) {
            byte[] bytes = cr.getBytes();
            FileOutputStream out = new FileOutputStream(filename);
            out.write(bytes);
            System.out.println("下载成功,返回主界面!");
        } else {
            System.out.println("下载失败,没有此文件!");
        }
        fileMain();
        close();
    }

    /*
     * 删除文件
     */
    public void delete() throws Exception {
        System.out.println("***********删除文件************");
        System.out.print("请输入要删除文件的编号:");
        FileEntity fe = new FileEntity();
        fe.setId(input.nextInt());
        CommandRelay cr = new CommandRelay();
        cr.setCommand("delete");
        cr.setFileObject(fe);
        socket = new Socket("localhost", 8722);
        sendData(cr);
        cr = getData();
        if (cr.isFlag()) {
            System.out.println("删除成功,返回主界面!");
        } else {
            System.out.println("删除失败,没有此文件!");
        }
        fileMain();
        close();
    }

    /*
     * 关闭资源
     */
    public void close() {
        input.close();
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        Client client = new Client();
        System.out.println("*****欢迎使用xk文件上传下载器*****");
        String flag = null;
        while (true) {
            System.out.print("1.登陆\n2.注册\n3.退出\n请输入: ");
            flag = client.input.next();
            switch (flag) {
            case "1":
                client.login();
                break;
            case "2":
                client.register();
                break;
            case "3":
                System.out.println("欢迎下次使用,再见!");
                System.exit(0);
                break;
            default:
                System.out.println("输入指令不正确,请重新输入");
                continue;
            }
            break;
        }
    }
}
运行效果

32人推荐
随时随地看视频
慕课网APP

热门评论

文件下载那里最后返回的应该是baos.toByteArray(),参考这个代码的童鞋注意啦!

我想问下,你下载下来的文件可以打不开吗,我的打不开,里面是空的,但是属性里面写占用了31m


我想问一下,数据库中的数据库和表的结构是什么样的,能发出来参考下吗?

查看全部评论