javase练手题四


  1. 基于学生信息管理系统增加以下两个功能:

         a.自定义学号异常类和年龄异常类,并在该成员变量不合理时产生异常对象并抛出。 
    
         b.当系统退出时将 List 集合中所有学生信息写入到文件中,当系统启动时读取文件中所 有学生信息到 List 集合中。
    

/*

在原来第三次试题上进行改动

年龄异常类

public class AgeExpection extends Exception {
    private static final long serialVersionUID = -2749056776334023828L;
    public AgeExpection() {
    }

    public AgeExpection(String message) {
        super(message);
    }
}

id异常类

public class IdExpection extends Exception  {
    private static final long serialVersionUID = -2261391088026045074L;
    public IdExpection() {
    }

    public IdExpection(String message) {
        super(message);
    }
}

读操作

public class Readlist {
    public static List readlist(){
        ObjectInputStream in=null;
        List list=null;
        try {
            in = new ObjectInputStream(new FileInputStream("./student.txt"));
            Object o = in.readObject();
            list=(List) o;

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (null!=in){
                try {
                    in.close();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        return list;
    }

}

写操作

public class Writelist {
    public static void writelist(List list){
        ObjectOutputStream out=null;
        try {
            out=new ObjectOutputStream(new FileOutputStream("E:\\lagou\\test_04\\student.txt"));
            out.writeObject(list);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (out!=null){
                try {
                    out.close();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

    }
}

总结 :其他的不做改动,只需开启系统之前讲文件中的对象读入集合中,关闭时候写入文件,直接点用即可,异常这块只需将系统中使用id 和 age字段的代码进行异常处理即可,在student类中setid和setage方法体中使用throw new xxxexpection(操作即可)

2.实现将指定目录中的所有内容删除,包含子目录中的内容都要全部删除。

删除文件的操作

public class De_file {
    public static void de(String src){
        File file=new File(src);
        if (!file.exists()){
            System.out.println("目录不存在");
            return;
        }

        for (File f : file.listFiles()){
            if (f.isFile()){
                f.delete();
            }else {
                De_file.de(f.getAbsolutePath());//递归进行删除文件夹中的文件操作
            }
        }
        file.delete();//最后删除文件夹
        System.out.println(file.getName()+"删除成功!");

    }
}

测试类

public class Test_2 {
    public static void main(String[] args) {

        //调用删除方法
        De_file.de("E:\\lagou\\1");
    }

3.使用线程池将一个目录中的所有内容拷贝到另外一个目录中,包含子目录中的内容。
Copy_Folders 类

public class Copy_Folders {
    public static void Copy(String path1,String path2){
        File file=new File(path1);
        File file1=new File(path2);
        if (!file.exists()){
            System.out.println("目录不存在!");
            return;
        }

        if (!file1.exists()) {
            file1.mkdirs();
            System.out.println(file1 + "  复制成功");
        }


        //创建一个线程池
        ExecutorService service= Executors.newFixedThreadPool(10);

        for (File f :file.listFiles()){
            service.submit(() -> {
            if (f.isFile()){
                CopyFile.Copy(f.getAbsolutePath(), file1.getAbsolutePath() + "/" + f.getName());
                System.out.println(f.getName()+   "复制成功");
            }else {
                Copy_Folders.Copy(f.getAbsolutePath(), file1.getAbsolutePath() + "/" + f.getName());
            }
        });

        }

        service.shutdown();

    }

复制文件操作

public class CopyFile {
    public static void Copy(String path1,String path2){
        BufferedReader br=null;
        BufferedWriter bw=null;
        try {
             br=new BufferedReader(new FileReader(path1));
             bw=new BufferedWriter(new FileWriter(path2));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String str=null;
        try {
            while ((str=br.readLine())!=null){
                bw.write(str);
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (null!=bw){
                    bw.close();
                }
                if (null!=br){
                    br.close();
                }
              ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

测试类

public class Test_03 {
    public static void main(String[] args) {
        //调用擦copy方法
        Copy_Folders.Copy("E:\\lagou\\4","E:\\lagou\\2");

    }
}

*** 第四题

  • 使用基于 tcp 协议的编程模型实现将 UserMessage 类型对象由客户端发送给服务器;
  • 服 务 器接 收到 对象 后判 断 用户 对象 信息 是否 为 “admin” 和 “123456”,
  • 若 是则 将 UserMessage 对象中的类型改为"success",否则将类型改为"fail"并回发给客户端,
  • 客户 端接收到服务器发来的对象后判断并给出登录成功或者失败的提示。
  • 其中 UserMessage 类的特征有:类型(字符串类型) 和 用户对象(User 类型)。
  • 其中 User 类的特征有:用户名、密码(字符串类型)。
  • 如:
  • UserMessage tum = new UserMessage(“check”, new User(“admin”, “123456”));
    /***
    user类
public class User implements Serializable{
    private static final long serialVersionUID = -2749056776334023828L;
    private String username;
    private String pasword;

    public User() {
    }

    public User(String username, String pasword) {
        this.username = username;
        this.pasword = pasword;
    }

    public String getUsername() {
        return username;
    }

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

    public String getPasword() {
        return pasword;
    }

    public void setPasword(String pasword) {
        this.pasword = pasword;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (username != null ? !username.equals(user.username) : user.username != null) return false;
        return pasword != null ? pasword.equals(user.pasword) : user.pasword == null;
    }

    @Override
    public int hashCode() {
        int result = username != null ? username.hashCode() : 0;
        result = 31 * result + (pasword != null ? pasword.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", pasword='" + pasword + '\'' +
                '}';
    }
}

UserMessage类

public class UserMessage implements Serializable {
    private static final long serialVersionUID = 8362793855078828309L;
    private String TYPE;
    private User user;

    public UserMessage() {
    }

    public UserMessage(String TYPE, User user) {
        this.TYPE = TYPE;
        this.user = user;
    }

    public String getTYPE() {
        return TYPE;
    }

    public void setTYPE(String TYPE) {
        this.TYPE = TYPE;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        UserMessage that = (UserMessage) o;

        if (TYPE != null ? !TYPE.equals(that.TYPE) : that.TYPE != null) return false;
        return user != null ? user.equals(that.user) : that.user == null;
    }

    @Override
    public int hashCode() {
        int result = TYPE != null ? TYPE.hashCode() : 0;
        result = 31 * result + (user != null ? user.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "UserMessage{" +
                "TYPE='" + TYPE + '\'' +
                ", user=" + user +
                '}';
    }
}

Client 类

public class Client {
    public static void main(String[] args) {
        ObjectInputStream in = null;
        ObjectOutputStream out = null;
        Socket s=null;
        try {
            s = new Socket("127.0.0.1", 8888);
            System.out.println("客户端启用~~");
            User user=new User("admin","123456");
            UserMessage um=new UserMessage();
            um.setUser(user);
            // 创建对象输出流
            out = new ObjectOutputStream(s.getOutputStream());
            // 发出对象
            out.writeObject(um);
            // 创建对象输入流
            in = new ObjectInputStream(s.getInputStream());
            // 获取服务端返回的UserMessage对象
            um = (UserMessage)in.readObject();
            // 打印结果
            if ("success".equals(um.getTYPE())) {
                System.out.println("登陆成功");
            }else{
                System.out.println("登陆失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (null!=in){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null!=in){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null!=s){
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }


    }
}

Server 类

public class Server {
    public static void main(String[] args){
        ObjectOutputStream out=null;
        ObjectInputStream  in=null;
        ServerSocket ss=null;
        Socket accept = null;
        try {
            ss=new ServerSocket(8888);
            System.out.println("服务器启动_监听中");
            Thread.sleep(1000);
            accept = ss.accept();
            in=new ObjectInputStream(accept.getInputStream());
            Object o = in.readObject();
            //流对象强制转换
            UserMessage msg=(UserMessage)o;
            User user = msg.getUser();
            //判断
            if ( "admin".equals(user.getUsername())&&"123456".equals(user.getPasword())){
                msg.setTYPE("success");
            }else {
                msg.setTYPE("fail");
            }
            out=new ObjectOutputStream(accept.getOutputStream() );
            out.writeObject(msg);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != accept) {
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ss) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }


}

5.使用基于 tcp 协议的编程模型实现多人同时在线聊天和传输文件,要求每个客户端将发 送的聊天内容和文件发送到服务器,服务器接收到后转发给当前所有在线的客户端。

服务端

public class Server {
    public static void main(String[] args) {
        // 创建服务端对象
        Server s = new Server(8888);
        // 开始服务
        s.begin();

    }

    private ServerSocket ss = null;
    private Socket s = null;
    // 定义一个集合储存连接的socket,以便转发给所有连接转发消息与文件
    private static List<Socket> socketList = new ArrayList<>();
    private String path;

    public Server(int port) {
        // 创建一个文件夹,存放收到的文件
        path = createFolders("./code/files/server/");
        // 启动服务
        try {
            ss = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 开始服务主程序
    public void begin() {
        System.out.println("等待客户端的连接请求...");
        try {
            // 无限循环,持续服务
            while (true) {
                // 获取连接
                s = ss.accept();
                // 储存连接至集合
                socketList.add(s);
                System.out.println("客户端" + s.getInetAddress() + "连接成功!");
                // 待定:需要执行的任务
                task(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != ss) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    // 创建文件夹功能
    public String createFolders(String path) {
        File folders = new File(path);
        if (!folders.exists()) {
            folders.mkdirs();
        }
        return folders.getAbsolutePath();
    }



    public void task(Socket socket) {
        // 接受到的客户端连接,都新建一个线程进行服务
        new Thread(() -> {
            // 定义输入输出流流
            DataInputStream in = null;
            DataOutputStream out = null;
            try {
                in = new DataInputStream(socket.getInputStream());
                out = new DataOutputStream(socket.getOutputStream());
                // 持续通信
                while (true) {
                    // 读取客户端发来的文本
                    String str = in.readUTF();
                    System.out.println(str);
                    // 打印
                    System.out.println("客户端" + s.getInetAddress() +": "+ str);
                    // 拆分文本内容
                    String type = str.split(":")[0];// 类型
                    int messageLen = Integer.valueOf(str.split(":")[2]);// 消息长度
                    String message = str.split(":")[3];// 消息
                    // 如果消息类型为chat,则进入聊天服务处理块
                    if ("chat".equalsIgnoreCase(type)) {
                        // 转发收到的消息
                        for (Socket s : socketList) {
                            DataOutputStream outAll = new DataOutputStream(s.getOutputStream());
                            outAll.writeUTF(str);
                        }
                        // 如果收到的消息是bye,则退出while循环,即结束连接
                        if ("bye".equalsIgnoreCase(message)) {
                            System.out.println("客户端" + s.getInetAddress() + "已下线!");
                            break;
                        }
                    }
                    // 如果发来的消息type为file,则进入文件处理块
                    if ("file".equalsIgnoreCase(type)) {
                        System.out.println("开始接收文件");
                        // 以收到的消息在服务端文件目录创建同样的文件
                        File f = new File(path, message);
                        // 创建文件输入流
                        FileOutputStream output = null;
                        output = new FileOutputStream(f);
                        byte[] bArr = new byte[8 * 1024];
                        int res = 0;
                        System.out.println("开始写入文件");
                        System.out.println("文件长度为" + messageLen);
                        while (true) {
                            // 读取客户端发来的数据
                            res = in.read(bArr, 0, bArr.length);
                            // 写入文件
                            output.write(bArr, 0, res);
                            output.flush();
                            System.out.println("已经写入:" + f.length());
                            // 如果文件的长度等于发来的消息给定的长度,则退出循环
                            if (f.length() == messageLen) {
                                System.out.println("文件接收完毕");
                                break;
                            }
                        }
                        if (null != output) {
                            // 关闭文件输入流
                            output.close();
                        }
                        // 转发文件
                        for (Socket s : socketList) {
                            // 不转发当前客户端
                            if (s.equals(socket)) {
                                continue;
                            }
                            // 创建输出流
                            DataOutputStream outAll = new DataOutputStream(s.getOutputStream());
                            outAll.writeUTF(str);
                            // 指向服务端目录下刚收到的文件
                            f = new File(path, message);
                            // 服务端发出消息,消息为刚接受的消息,即包含了类型、长度、文件名,以便客户端进行判断处理
                            out.writeUTF(str);
                            FileInputStream input = null;
                            // 创建文件输入流
                            input = new FileInputStream(f);
                            // 读取并输出文件数据
                            while ((res = input.read(bArr)) != -1) {
                                outAll.write(bArr, 0, res);
                                outAll.flush();
                            }
                            if (null != input) {
                                // 关闭文件输入流
                                input.close();
                            }
                        }
                        System.out.println("文件转发完毕");
                    }


                }
                // 连接结束时,从集合中移除该socket对象
                socketList.remove(socket);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != in) {

                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != out) {

                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


    }


}

客户端

public class Client {
    private DataInputStream in;
    private DataOutputStream out;
    private Scanner sc;
    private String user;
    private String path;

    public Client(String user, Socket socket) {
        // 定义客户端标识
        setUser(user);
        // 创建保存接收的文件
        path = createFolders("./code/files/" + user + "/");
        try {
            // 创建输入输出流
            in = new DataInputStream(socket.getInputStream());
            out = new DataOutputStream(socket.getOutputStream());
            // 获取终端输入
            sc = new Scanner(System.in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setUser(String user) {
        this.user = user;
    }

    // 创建一个线程,发送消息
    public Thread send() {
        Thread s = new Thread(() -> {
            System.out.println("登陆成功");
            while (true) {
                // 获取终端输入
                String str = sc.next();
                try {
                    // 约定,输入file进行发送文件操作,其他为普通消息
                    if ("file".equalsIgnoreCase(str)) {
                        System.out.println("请输入文件名");
                        str = sc.next();
                        // 获取要发送的文件
                        File f = new File(path, str);
                        if (!f.exists()) {
                            System.out.println("文件不存在");
                            continue;
                        }
                        // 构建文件基本信息发出:消息类型+用户名+文件长度+文件名,以便服务端进行判断处理
                        out.writeUTF("file:" + user + ":" + String.valueOf(f.length()) + ":" + str);
                        // 读取文件并发出
                        FileInputStream input = null;
                        input = new FileInputStream(f);
                        byte[] bArr = new byte[8 * 1024];
                        int res = 0;
                        while ((res = input.read(bArr)) != -1) {
                            out.write(bArr, 0, res);
                            out.flush();
                        }
                        if (null != input) {
                            input.close();
                        }
                        System.out.println("文件发送成功");

                    } else {
                        // 发送普通消息:消息类型+用户名+字符串长度+消息,以便服务端进行判断处理
                        out.writeUTF("chat:" + user + ":" + String.valueOf(str.length()) + ":" + str);
                        // 退出机制
                        if ("bye".equalsIgnoreCase(str)) {
                            System.out.println("聊天结束!");
                            break;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        );
        return s;
    }

    // 创建一个线程,接受消息
```java
    public Thread receive() {
        Thread r = new Thread(() -> {
            while (true) {
                String str = "";
                try {
                    // 获取消息,并进行拆分
                    str = in.readUTF();
                    String type = str.split(":")[0];
                    String user = str.split(":")[1];
                    int messageLen = Integer.valueOf(str.split(":")[2]);
                    String message = str.split(":")[3];
                    // 如果消息类型为chat,则进行打印操作
                    if ("chat".equalsIgnoreCase(type)) {
                        if ("bye".equalsIgnoreCase(message)) {
                            break;
                        }
                        // 仅仅打印消息中的user与消息内容
                        System.out.println(user + ":" + message);
                    }
                    // 接收文件
                    if ("file".equalsIgnoreCase(type)) {
                        // 不接收自己发出的文件
                        if (this.user.equals(user)) {
                            continue;
                        }
                        System.out.println("收到"+user+"的文件:"+message);
                        // 创建文件,并将收到的数据写入
                        File f = new File(path, message);
                        FileOutputStream output = null;
                        output = new FileOutputStream(f);
                        byte[] bArr = new byte[8 * 1024];
                        int res = 0;
                        while (true) {
                            res = in.read(bArr, 0, bArr.length);
                            output.write(bArr, 0, res);
                            output.flush();
                            // 如果文件长度等于发来消息告知的长度,则结束写入
                            if (f.length()==messageLen) {
                                break;
                            }
                        }
                        if (null != output) {
                            output.close();
                        }


                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        });
        return r;
    }


    // 关闭各种流
    public void close() {
        if (null != in) {

            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != out) {

            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != sc) {

            sc.close();
        }

    }

    // 创建目录方法
    public String createFolders(String path) {
        File folders = new File(path);
        if (!folders.exists()) {
            folders.mkdirs();
        }
        return folders.getAbsolutePath();
    }

}

测试类

public class Test_01 {
    public static void main(String[] args) {
        Socket socket = null;
        try {

            // 建立连接
            socket = new Socket("127.0.0.1", 8888);
            System.out.println(socket);
            // 创建客户端对象
            Client user = new Client("关公",socket);
            // 开始消息的交互
            Thread s = user.send();
            Thread r =user.receive();
            s.start();
            r.start();
            s.join();
            r.join();
            // 关闭各种流
            user.close();
        } catch ( InterruptedException|IOException e) {
            e.printStackTrace();
        }finally{
            if (null!=socket) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


测试截图
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值