第一阶段模块四作业

  1. 编程题

a.使用 List 集合实现简易的学生信息管理系统,要求打印字符界面提示用户选择相应的功 能,根据用户输入的选择去实现增加、删除、修改、查找以及遍历所有学生信息的功能。

b.自定义学号异常类和年龄异常类,并在该成员变量不合理时产生异常对象并抛出。

c.当系统退出时将 List 集合中所有学生信息写入到文件中,当系统启动时读取文件中所 有学生信息到 List 集合中。
Student.java

package com.lagou.task22.Student;

import java.io.Serializable;
import java.util.Objects;

/**
 *    a.使用 List 集合实现简易的学生信息管理系统,要求打印字符界面提示用户选择相应的功 能,根据用户输入的选择去实现增加、删除、修改、查找以及遍历所有学生信息的功能。
 *
 *    b.自定义学号异常类和年龄异常类,并在该成员变量不合理时产生异常对象并抛出。
 *
 *    c.当系统退出时将 List 集合中所有学生信息写入到文件中,当系统启动时读取文件中所 有学生信息到 List 集合中。
 */
public class Student implements Serializable {
    private static final long serialVersionUID = 3556670203632481549L;
    private int id;
    private String name;
    private int age;

    public Student() {
    }

    public Student(int id, String name, int age) throws Exception{
        setId(id);
        setName(name);
        setAge(age);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) throws StudentIDException {
        if (id > 0 && id < 999){
            this.id = id;
        }else {
            throw new StudentIDException("学号不合理哦!");
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) throws AgeException {
        if (age > 0 && age < 150){
            this.age = age;
        }else {
            throw new AgeException("年龄不合理哦!");
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return id == student.id &&
                age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, age);
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

StudentTest.java

package com.lagou.task22.Student;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class StudentTest extends AdditionsDeletionsModifications {

    public static void main(String[] args) throws Exception {

        List<Student> list =new LinkedList();

        AdditionsDeletionsModifications adm = new AdditionsDeletionsModifications();

        // 指向学生集合文件
        File txt = null;
        try {
            txt = new File("/Users/pingmao/Desktop/捣乱2/a.txt");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (txt.exists()) {
            if (ReadList.rdList() != null){
                list = ReadList.rdList();
                System.out.println(list);
            }else {
                System.out.println("为空");
            }
        }else{
            // 如果不存在则创建一个新集合
            list = new LinkedList<>();
        }


        while (true) {
            // 1、绘制字符界面
            System.out.println("           欢迎来到学生信息管理系统");
            System.out.println("------------------------------------------");
            System.out.println("           请输入你要操作的选项");
            System.out.print("[0]退出系统" + " ");
            System.out.print("[1]增加学生信息" + " ");
            System.out.print("[2]删除学生编号" + " ");
            System.out.print("[3]修改学生信息" + " ");
            System.out.print("[4]编号查找学生信息" + " ");
            System.out.println("[5]查看所有学生信息" + " ");
            System.out.println("------------------------------------------");
            Scanner sc = new Scanner(System.in);
            int choose = sc.nextInt();

            // 2.使用swith case分支结构来模拟用户的选择并给出提示
            switch (choose) {
                case 0:
                    System.out.println("正在退出学员系统...");
                    WriteList.wrList(list);
                    break;
                case 1:
                    // 增加学生信息
                    System.out.println("增加学生信息...,请输入id、姓名、年龄、");
                    System.out.println("输入id");
                    int id = sc.nextInt();
                    System.out.println("输入姓名");
                    String name = sc.next();
                    System.out.println("输入年龄");
                    int age = sc.nextInt();
                    adm.stu_add(id, name, age,list);
                    break;
                case 2:
                    // 删除学生信息
                    System.out.println("删除学生信息");
                    System.out.println("输入需要删除的id");
                    id = sc.nextInt();
                    adm.deletions(list, id);
                    break;

                case 3:
                    // 修改学生信息
                    System.out.println("修改学生信息");
                    id = sc.nextInt();
                    Student getStudent = adm.Numbering(id, list);
                    if (null == getStudent){
                        System.out.println("无对象!");
                        break;
                    }
                    System.out.println("输入id");
                    id = sc.nextInt();
                    System.out.println("输入姓名");
                    name = sc.next();
                    System.out.println("输入年龄");
                    age = sc.nextInt();
                    adm.modifications(id, name, age,getStudent);
                    break;

                case 4:
                    System.out.println("编号查找学生信息,请输入id");
                    id = sc.nextInt();
                    Student numbering = adm.Numbering(id,list);
                    if (null == numbering){
                        System.out.println("无对象!");
                    }else {
                        System.out.println("查询成功" + numbering);
                    }

                case 5:
                    // 打印所有学生信息
                    System.out.println("所有学生信息");
                    System.out.println(list);
                    break;

                default:
                    System.out.println("输入错误,请重新选择!");
            }
            if (0 == choose)
                break;
        }
    }
}



AgeException.java

package com.lagou.task22.Student;

/**
 * 年龄异常类
 */
public class AgeException extends Exception {

    static final long serialVersionUID = 7818375828146099155L;  // 序列化的版本号,与序列化操作有关系

    public AgeException() {
    }

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

AdditionsDeletionsModifications.java

package com.lagou.task22.Student;

import java.util.List;

/**
 * 提供现增加、删除、修改、查找以及遍历所有学生信息的功能
 */

public class AdditionsDeletionsModifications {

    //List<Student> list =new ArrayList();

    // 增加学生信息
    public static void stu_add(int id, String name, int age,List<Student> list) throws Exception {
        Student newStudent = new Student(id, name, age);
        boolean flag = list.contains(newStudent);
        if (flag) {
            System.out.printf("学号%d已经存在,添加失败\n", id);

        } else {
            list.add(newStudent);
            System.out.printf("%s添加成功\n", name);
        }
    }

    // 删除学生信息
    public void deletions(List<Student> list, int id) {
        for (Student ts : list) {
            int index = list.indexOf(ts);
            if (id == ts.getId()) {
                // 删除
                list.remove(index);
                System.out.printf("%d删除成功\n", ts.getId());
            }

        }

    }

    // 修改学生信息
    public void modifications(int id, String name, int age, Student student) throws Exception {
        student.setId(id);
        student.setAge(age);
        student.setName(name);
        System.out.println("修改成功!");

    }

    // 查找学生信息
    public static Student Numbering(int id,List<Student> list) {
        for (Student st: list){
            if (id == st.getId()){
                return st;
            }
        }

        return null;
    }
    // 遍历学生信息

    public void Find(List<Student> list) {

        for (Student ts: list) {
            System.out.println(ts);
        }

    }





}

ReadList.java

package com.lagou.task22.Student;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

public class ReadList {

    public static List<Student> rdList() {
        ObjectInputStream in = null;
        List<Student> list =null;

        try {
            in = new ObjectInputStream(new FileInputStream("/Users/pingmao/Desktop/捣乱2/a.txt"));
            // 读取文件
            Object obj = in.readObject();
            // 获取集合对象
            list = (List<Student>)obj;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 返回集合对象
        return list;
    }
}

WriteList.java

package com.lagou.task22.Student;

import com.lagou.task22.Student.Student;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;

public class WriteList {

    public static void wrList(List<Student> list) {
        ObjectOutputStream out = null;

        try {
            out = new ObjectOutputStream(new FileOutputStream("/Users/pingmao/Desktop/捣乱2/a.txt"));
            // 写入集合对象
            out.writeObject(list);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

  1. 编程题

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

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

CopyHomework.java

package com.lagou.task22.CopyDelete;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 编程题
 *
 *     a. 使用线程池将一个目录中的所有内容拷贝到另外一个目录中,包含子目录中的内容。
 *
 *     b.实现将指定目录中的所有内容删除,包含子目录中的内容都要全部删除。
 */
public class CopyHomework {

    static File copyFromFile = new File("/Users/pingmao/Desktop/捣乱2");
    static File copyToFile = new File("/Users/pingmao/Desktop/捣乱3");

    public static void main(String[] args) {
        System.out.println("拷贝开始......");
        copy(copyFromFile,copyToFile);
        /*System.out.println(Thread.currentThread().getName() +":"+"CP "+copyFromFile+"-->"+copyToFile);*/
        System.out.println("拷贝结束......");

    }

    public static void copy(File copyFromFile,File copyToFile) {

        File[] files = copyFromFile.listFiles();
        ExecutorService service= Executors.newFixedThreadPool(10);
        for (int i = 0; i < files.length; i++){
            File file = files[i];
            File fileTo = new File(copyToFile,file.getName());
            service.submit(() ->{
                if (file.isFile()){
                    // 执行拷贝
                    System.out.println(Thread.currentThread().getName() +":"+"拷贝 "+copyFromFile+"-->"+copyToFile);
                    try {
                        // 读取输入流
                        FileInputStream fis = new FileInputStream(file);
                        // 创建输出流
                        // 目标文件夹创建
                        if (!copyToFile.exists()){
                            copyToFile.mkdirs();
                        }
                        // 创建输出文件的全路径名字
                        FileOutputStream fos = new FileOutputStream(fileTo);
                        // 执行拷贝
                        byte[] bytes = new byte[1024*8];
                        int len = 0;
                        while ((len = fis.read(bytes))!=-1){
                            fos.write(bytes,0,len);
                        }
                        fos.close();
                        fis.close();
                    } catch (Exception e) {
                        //System.out.println(Thread.currentThread().getName() +":"+"File Already Exsited!");
                        e.printStackTrace();
                    }
                }else {
                    copy(file,fileTo);
                }
            });

        }
        service.shutdown();

    }
}

DeleteFile.java

package com.lagou.task22.CopyDelete;

import java.io.File;

/**
 * b.实现将指定目录中的所有内容删除,包含子目录中的内容都要全部删除。
 */
public class DeleteFile {

    public static void DeleteFile(File[] files) {
        if (null == files) return;
        // foreach遍历目录元素并删除
        for (File file: files) {
            if (file.isFile()){
            // 如果是文件类型是文件则删除
            file.delete();
            System.out.println("删除文件[" + file.getAbsolutePath() +"]成功!");

            }else if (file.isDirectory()){
                // 文件类型是目录则删除目录中的文件
                DeleteFile(file.listFiles());
            }
        }
    }

    public static void main(String[] args) {
        File file = new File("/Users/pingmao/Desktop/捣乱3");
        DeleteFile(file.listFiles());

    }
}

  1. 编程题

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

ServerInit.java

package com.lagou.task22.TCP;
import com.lagou.task22.test.ServerThread;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

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

public class ServerInit {
    private static List<Socket> sockets = new ArrayList<>();//创建一个集合存储客户端的socket
    private static ServerSocket ss = null;
    private static Socket s = null;
    public static void main(String[] args) {
        ServerInit();
    }
    //连接客户端开始服务
    public static void ServerInit(){
        while (true){
            try {
                ss =  new ServerSocket(8888);
                System.out.println("等待连接客户端连接....");
                s= ss.accept();//接收客户端的连接并赋值给Socket
                sockets.add(s);
                System.out.println("客户端"+s.getInetAddress()+"连接成功");
                //每连接一个客户使用一个线程为之服务
                new ServerThread(sockets,s).start();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

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

ServerThreadInit.java

package com.lagou.task22.TCP;

import javax.print.DocFlavor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.List;

public class ServerThreadInit extends Thread {

    private List<Socket> sockets;
    private BufferedReader br;

    private Socket s; // 合成复用原则
    public ServerThreadInit(List<Socket> sockets,Socket s){
        this.sockets = sockets;
        this.s = s;
    }

    @Override
    public void run(){

        try {
            br = new BufferedReader(new InputStreamReader(s.getInputStream())); // 获取输入流接收数据

            while (true){
                // 实时对客户端发来的字符串内容的接收并打印
                // 当没有数据发来时候
                String s1 = br.readLine();
                System.out.println(s1);
                /*String[] strings = s1.split(":");
                System.out.println("客户端" + strings[0] + "发来的字符串内容是:" + strings[1]);*/
                //InetAddress inetAddress = s.getInetAddress();
                System.out.println("客户端" + s.getInetAddress() + "发来的字符串内容是:" + s1);
                for (Socket socket: sockets){
                    boolean flag = false;
                    try {
                        flag = socket.getKeepAlive();
                    } catch (Exception e){
                        continue;
                    }
                    if (!flag){
                        PrintStream ps = new PrintStream(socket.getOutputStream()); //获取输出流回发数据
                        ps.println(s1);
                        ps.flush();
                    }
                }
                System.out.println("已经将发来的消息" + s1 + "转发给其他客户端!");
                // 当客户端发送来的内容为 bye 时,则聊天结束
                if ("bye".equalsIgnoreCase(s1)){
                    System.out.println("客户端" + s.getInetAddress() + "已下线!");
                    break;
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null != s){
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null !=br ){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

ClientInit.java

package com.lagou.task22.TCP;

import com.lagou.task10.StaticOuter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientInit {
    private String user;//客户端标识
    private PrintStream ps= null;
    private BufferedReader br = null;
    private Scanner sc = null;
    private String str ;
    public ClientInit(String user,Socket socket){
        try {
            this.user = user;
            ps = new PrintStream(socket.getOutputStream());//打印流
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));//输入流
            sc = new Scanner(System.in);//保证一直处于可输入状态
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //启用一个线程,用于发送消息
    public Thread send(){
        Thread threadSend = new Thread(){
            @Override
            public void run() {
                while (true){
                    str= sc.next();//获取键盘输入信息
                    ps.println(user+":"+str);//将用户名和输入信息一起发送给服务器
                    ps.flush();
                    if ("bye".equalsIgnoreCase(str)){
                        System.out.println("退出聊天室");
                        break;
                    }

                }
            }


        };
        return threadSend;
    }
    //接收消息线程
    public Thread receive(){
        Thread threadReceive = new Thread(){
            @Override
            public void run() {
                while (true){

                    String s = null;//读取服务器传来的消息
                    try {
                        s = br.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //进行消息拆分
                    String[] strings = null;
                    try {
                        strings = s.split(":");//以:作为拆分点
                    }catch (Exception e){
                        break;
                    }

                    if (user.equalsIgnoreCase(strings[0])){
                        System.out.println("我:"+strings[1]);//如果是本人发送的消息,此客户端界面显示我:+消息
                        continue;
                    }
                    System.out.println(strings[0]+":"+strings[1]);//否则显示user+消息
                    if ("bye".equalsIgnoreCase(strings[1])){
                        break;//如果服务端传来的时bye 则跳出循环
                    }
                }



            }


        };
        return threadReceive;
    }
    //关闭流
    public void close(){
        if (null!=null){
            sc.close();
        }
        if (null!=br){
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null!=ps){
            ps.close();
        }
    }
}

Client01.java

package com.lagou.task22.TCP;

import java.io.IOException;
import java.net.Socket;

public class Client01 {
    public static void main(String[] args) {
        Socket socket = null;
        System.out.println("===========欢迎来到拉勾聊天室===========");
        try {
            socket = new Socket("127.0.0.1",8888);
            System.out.println("    正在连接服务器....连接服务器成功    ");
            ClientInit c1 = new ClientInit("小明",socket);//创建一个客户端实例
            Thread t1 = c1.send();//获取发送消息线程
            Thread t2 = c1.receive();//获取接收消息线程
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            c1.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //关闭socket
            if (null!=socket){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值