Java实战之基于I/O流设计的图书管理系统

目录一、前言二、项目介绍三、项目说明四、项目实现五、总结

一、前言

当前,我还没有学到数据库相关的知识,想要完全通过Java来完成一个可以存储数据的图书馆管理系统就只能使用I/O流的知识,将内容都保存到文件中,再进行增删改查的操作,这就很考验我们的Java基础知识掌握能力。

二、项目介绍 Java基本语法的掌握 流程控制语句的熟练使用 面向对象思想的理解 能否熟练使用封装、继承、多态 接口、异常的熟悉 集合的使用 是否熟悉掌握I/O流相关操作

三、项目说明 传统的人工管理图书馆流程繁琐,我们需求设计一个图书馆管理系统来方便学生借书以及管理员管理书籍 系统功能分为:读者信息管理模块、图书信息管理模块、图书借阅管理模块、基础信息维护模块和用户管理模块。 读者信息管理:能对读者基本信息管理,如:新增读者、信息修改、查询 图书信息管理:能管理图书基本信息,如新增图书、删除图书、查询图书等 图书借阅信息管理:能对借阅信息进行记录,包括读者信息、图书信息、借阅时间等。 图书归还信息管理:能对图书归还信息进行判断,是否超出借阅时间,罚金为多少

四、项目实现

代码部分如下:

Person类:

package User;public class Person {    public String name;//姓名    public String sex;//性别    public int age;//年龄    public Person() {    }    public Person(String name, String sex, int age) {        this.name = name;        this.sex = sex;        this.age = age;    }    public void setName(String name) {        this.name = name;    }    public String getName() {        return name;    }    public void setSex(String sex) {        this.sex = sex;    }    public String getSex() {        return sex;    }    public void setAge(int age) {        this.age = age;    }    public int getAge() {        return age;    }}

Book类:

package Book;public class Book {    private String bookName; //书名    private String author; //作者    public double price; //价格    private String category; //分类    public String press;//出版社    private String state; //状态  true-已借出  false-未借出    private String borrowName;    private String borrowTime;        public Book() {    }    public Book(String bookName, String author, double price, String category, String press, String state, String borrowName, String borrowTime) {        this.bookName = bookName;        this.author = author;        this.price = price;        this.category = category;        this.press = press;        this.state = state;        this.borrowName = borrowName;        this.borrowTime = borrowTime;    }    public String getName() {        return bookName;    }    public void setName(String bookName) {        this.bookName = bookName;    }    public String getAuthor() {        return author;    }    public void setAuthor(String author) {        this.author = author;    }    public double getPrice() {        return price;    }    public void setPrice(double price) {        this.price = price;    }    public String getCategory() {        return category;    }    public void setCategory(String category) {        this.category = category;    }    public String getPress() {        return press;    }    public void setPress(String press) {        this.press = press;    }    public String getState() {        return state;    }    public void setState(String state) {        this.state = state;    }    public String getBorrowName() {        return borrowName;    }    public void setBorrowName(String borrowName) {        this.borrowName = borrowName;    }    public String getBorrowTime() {        return borrowTime;    }    public void setBorrowTime(String borrowTime) {        this.borrowTime = borrowTime;    }    @Override    public String toString() {        return bookName + "," + author + "," + price + "," + category + "," + press + "," + state + "," + borrowName + "," + borrowTime;    }}

Library类:

package Library;import java.io.*;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Scanner;import User.User;import User.Admin;public class Library {    Scanner sc = new Scanner(System.in);    private String operator;    //用户注册登录    public void Interface() throws IOException, ParseException {        boolean a = true;        File file = new File("用户信息.txt");        try {            while (a) {                System.out.println("==================图书管理系统==================");                System.out.println("请登录:1.普通用户  2.管理员登录  3.注册 4.退出系统");                int i = sc.nextInt();                if (i < 1 || i > 4) {                    System.out.println("到底能不能行?能不能看明白了再输!");                } else if (i == 4) {                    a = false;                } else if (i == 1) {                    //普通用户登录                    System.out.println("请输入您的用户名:");                    operator = sc.next();                    System.out.println("请输入您的密码:");                    String password = sc.next();                    FileInputStream intput = new FileInputStream(file);                    BufferedReader reader = new BufferedReader(new InputStreamReader(intput));                    String tempString;                    List<String> list = new ArrayList<>();                    while ((tempString = reader.readLine()) != null) {                        list.add(tempString);                    }                    //判断输入的用户名是否存在                    boolean flag = false;                    String[] userinf = new String[5];                    for (String user : list) {                        userinf = user.split(",");                        if (operator.equals(userinf[0])) { //判断用户名是否存在                            flag = true;                            break;                        }                    }                    //如果存在,判断密码是否正确                    if (flag == true) {                        if (password.equals(userinf[1])) {                            System.out.println("登陆成功");                            //写日志                            Date nowDate = new Date();                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                            String returnTime = sdf.format(nowDate);                            File file2 = new File("日志.txt");                            FileWriter fw1 = new FileWriter(file2, true);                            fw1.write(returnTime + "  " + operator + "登录了");                            fw1.write(System.getProperty("line.separator"));//在段落后添加一个换行符                            fw1.close();                            //登录                            try {                                User user = new User();                                user.operation(userinf, operator);                            } catch (Exception e) {                                System.out.println("到底能不能行?能不能看明白了再输!");                                User user = new User();                                user.operation(userinf, operator);                            }                        } else {                            System.out.println("密码错误");                        }                    } else {                        System.out.println("用户名不存在");                    }                    intput.close();                    reader.close();                } else if (i == 2) {                    //管理员登录                    System.out.println("请输入管理员密码!");                    String rootPassword = sc.next();                    if (rootPassword.equals("88888888")) {                        //管理员登录成功                        System.out.println("管理员登陆成功!");                        try {                            Admin admin = new Admin();                            admin.admin();                        } catch (Exception e) {                            System.out.println("到底能不能行?能不能看明白了再输!");                            Admin admin = new Admin();                            admin.admin();                        }                    } else {                        System.out.println("你是不是管理员心里没个ACD数吗?");                    }                } else if (i == 3) {                    //注册                    System.out.println("请输入用户名:");                    String name = sc.next();                    //查找是否有同名用户                    FileInputStream intput = new FileInputStream(file);                    BufferedReader reader = new BufferedReader(new InputStreamReader(intput));                    String tempString;                    List<String> list = new ArrayList<>();                    while ((tempString = reader.readLine()) != null) {                        list.add(tempString);                    }                    String[] userinf = new String[5];                    boolean flag = false;                    for (String user : list) {                        userinf = user.split(",");                        if (name.equals(userinf[0])) { //判断用户名是否存在                            flag = true;                            System.out.println("该用户名已存在,请重新拟取名称");                            break;                        }                    }                    if (flag == false) {                        System.out.println("请输入密码:");                        String password = sc.next();                        String sex;                        while (true) {                            System.out.println("请输入您的性别:");                            sex = sc.next();                            if (sex.equals("男") || sex.equals("女")) {                                break;                            } else {                                System.out.println("请输入正确的性别!");                            }                        }                        System.out.println("请输入您的年龄:");                        int age = sc.nextInt();                        if (age < 10) {                            System.out.println("您的年龄太小啦!请让家长使用账号帮您借阅书籍!");                            break;                        }                        long phone;                        while (true) {                            System.out.println("请输入您的电话号码:");                            phone = sc.nextInt();                            if (phone < 0) {                                System.out.println("请输入正确的电话号码!");                            } else {                                break;                            }                        }                        User u = new User(name, sex, age, phone, password);                        file.createNewFile();                        FileWriter fw = new FileWriter(file, true);                        fw.write(u.toString());                        fw.write(System.getProperty("line.separator"));//在段落后添加一个换行符                        fw.close();                        System.out.println("恭喜您,注册成功!");                        Date nowDate = new Date();                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                        String returnTime = sdf.format(nowDate);                        File file1 = new File("日志.txt");                        FileWriter fileWriter = new FileWriter(file1, true);                        fileWriter.write(returnTime + "  注册了新用户:" + name);                        fileWriter.write(System.getProperty("line.separator"));//在段落后添加一个换行符                        fileWriter.close();                    }                }            }        } catch (Exception e) {            System.out.println("到底能不能行?能不能看明白了再输!");            Library library = new Library();            library.Interface();            return;        }    }}

添加书籍AddBook:

package Book;import java.io.*;import java.util.ArrayList;import java.util.List;import java.util.Scanner;public class AddBook {    public void addBook() throws IOException {        Scanner sc = new Scanner(System.in);        File file = new File("书籍.txt");        System.out.println("请输入书名:");        String bookName = sc.next();        //查找是否有同名书籍        FileInputStream intput = new FileInputStream(file);        BufferedReader reader = new BufferedReader(new InputStreamReader(intput));        String tempString;        List<String> list = new ArrayList<>();        while ((tempString = reader.readLine()) != null) {            list.add(tempString);        }        String[] bookinf = new String[8];        boolean flag = false;        for (String user : list) {            bookinf = user.split(",");            if (bookName.equals(bookinf[0])) { //判断书籍是否存在                flag = true;                System.out.println("该书籍已存在,小图书馆不整这么多一样的书了,浪费钱!");                break;            }        }        if (flag == false) {            System.out.println("请输入作者:");            String author = sc.next();            double price;            while (true) {                System.out.println("请输入书籍价格:");                price = sc.nextDouble();                if (price < 10) {                    System.out.println("这么便宜?要不然直接白送?能不能合理一点?");                } else if (price > 500) {                    System.out.println("这河里吗?这么金贵的书你舍得借吗?这么小个图书馆放这么贵的书河里吗?");                } else {                    break;                }            }            System.out.println("请输入书籍类型:");            String category = sc.next();            System.out.println("请输入书籍的出版社:");            String press = sc.next();            String state = "false";            String borrowName = "无";            String borrowTime = "null";            Book book = new Book(bookName, author, price, category, press, state, borrowName, borrowTime);            file.createNewFile();            FileWriter fw = new FileWriter(file, true);            fw.write(book.toString());            fw.write(System.getProperty("line.separator"));//在段落后添加一个换行符            fw.close();            System.out.println("恭喜您,添加书籍成功!");        }    }}

借阅书籍BorrowBook:

该类中使用了修改文本中特定字符串的内容的方法,该方法的使用探讨我已经写成博文发布,可以点击以下链接进行查看:Java中查找文本中特定内容后进行修改

package Book;import java.io.*;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Scanner;public class BorrowBook {    Scanner scanner = new Scanner(System.in);    public void borrowBook(String operator) throws IOException {        String filePath = "书籍.txt";        BorrowBook modifyFile = new BorrowBook();        File bookFile = new File("书籍.txt");        //根据书籍名称查询到需要修改的书籍数据        FileInputStream intput = new FileInputStream(bookFile);        BufferedReader reader = new BufferedReader(new InputStreamReader(intput));        String tempString = null;        List<String> list = new ArrayList<>();        while ((tempString = reader.readLine()) != null) {            list.add(tempString);        }        boolean flag = false;        String[] bookinf = new String[8];        System.out.println("=======================当前可借阅书籍有=======================");        int i = 0;        for (String user : list) {            bookinf = user.split(",");            if (bookinf[5].equals("false")) {                System.out.print(" | " + bookinf[0] + " |");                i++;                if (i % 5 == 0) {                    System.out.println("");                    System.out.println("==========================================================");                }            }        }        if (i % 5 != 0) {            System.out.println("");            System.out.println("==========================================================");        }        System.out.println("请输入要借阅的书籍名称:");        String bookName = scanner.next();        for (String user : list) {            bookinf = user.split(",");            if (bookName.equals(bookinf[0])) { //判断书籍是否存在                flag = true;                System.out.println("书名:" + bookinf[0] + ",作者:" + bookinf[1] + ",价格:" + bookinf[2] +                        ",类型:" + bookinf[3] + ",出版社:" + bookinf[4] + ",是否被借出:" + bookinf[5]);                break;            }        }        if (flag == false) {            System.out.println("没有查找到该书籍,请重新确认后再进行查找!");            return;        }        //修改书籍数据后,重新写入文件        if (bookName.equals(bookinf[0]) && bookinf[5].equals("false")) {            boolean result = modifyFile.writeFile(filePath, modifyFile.readFileContent(bookinf, filePath, "false", "true"));            // 修改文件中借阅状态            if (result == true) {                //获取借书人后写入“无”                modifyFile.writeFile(filePath, modifyFile.readFileContent(bookinf, filePath, "无", operator));                //获取时间后写入最后一位                Date nowDate = new Date();                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                String borrowTime = sdf.format(nowDate);                modifyFile.writeFile(filePath, modifyFile.readFileContent(bookinf, filePath, "null", borrowTime));                System.out.println("借阅成功!");//                System.out.println("借阅时间:" + borrowTime + ",最多可借阅7天,请记得按时归还!");                System.out.println("借阅时间:" + borrowTime + ",最多可借阅20秒,请记得按时归还!");//为方便测试,将借阅时间设置为20秒                //写日志                File file = new File("日志.txt");                FileWriter fw = new FileWriter(file, true);                fw.write(borrowTime + "  " + operator + "借走了图书:" + bookinf[0]);                fw.write(System.getProperty("line.separator"));//在段落后添加一个换行符                fw.close();                return;            }        } else {            System.out.println("该书已被借出或不存在,请重新查询后再进行借阅!");        }    }    // 读文件    public String readFileContent(String[] bookinf, String filePath, String oldString, String newString) {        Scanner sc = new Scanner(System.in);        BufferedReader br = null;        String line = null;        StringBuffer bufAll = new StringBuffer();// 保存修改过后的所有内容        try {            br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));            while ((line = br.readLine()) != null) {                StringBuffer buf = new StringBuffer();                // 修改内容核心代码                String[] bookinf2 = line.split(",");                if (bookinf2[0].equals(bookinf[0])) {//判断条件根据自己的要求修改                    buf.append(line);                    int indexOf = line.indexOf(oldString);                    buf.replace(indexOf, indexOf + oldString.length(), newString);// 修改内容                    buf.append(System.getProperty("line.separator"));// 添加换行                    bufAll.append(buf);                } else {                    buf.append(line);                    buf.append(System.getProperty("line.separator"));                    bufAll.append(buf);                }            }        } catch (Exception e) {            e.printStackTrace();        } finally {            if (br != null) {                try {                    br.close();                } catch (Exception e) {                    br = null;                }            }        }        return bufAll.toString();    }    // 写文件    public boolean writeFile(String filePath, String content) {        BufferedWriter bw = null;        try {            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"));            bw.write(content);            bw.flush();        } catch (Exception e) {            e.printStackTrace();            return false;        } finally {            if (bw != null) {                try {                    bw.close();                } catch (IOException e) {                    bw = null;                }            }        }        return true;    }}

删除书籍DeleteBook:

关于删除书籍中的删除文本文件中精确的某一行的方法详解可以参考我之前写过的博文:Java中删除文本文件中特定行的内容

package Book;import java.io.*;import java.util.ArrayList;import java.util.List;import java.util.Scanner;public class DeleteBook {    private String bookDelete;    String[] bookinf = new String[8];    String[] bookinf1 = new String[8];    public void deleteBook() throws IOException {        File file = new File("书籍.txt");        FileInputStream intput = new FileInputStream(file);        BufferedReader reader = new BufferedReader(new InputStreamReader(intput));        String tempString;//定义一个字符串,每一次读出该行字符串内容        List<String> list = new ArrayList<>();//定义一个list字符串集合用来储存每一行的字符串信息        while ((tempString = reader.readLine()) != null) {            list.add(tempString);        }        System.out.println("==========当前书籍有==========");        //遍历字符串集合        for (String book : list) {            bookinf = book.split(",");//将‘,‘作为分隔符,将字符串分隔开存放进入数组中            System.out.print(bookinf[0] + " ");        }        System.out.println("");        //输入要删除的内容        System.out.println("请输入要删除的书籍名称:");        Scanner scanner = new Scanner(System.in);        bookDelete = scanner.next();        //查询该用户是否有未归还的书籍,如果存在未归还的书籍,将不能删除该用户的信息        FileInputStream inputStream = new FileInputStream(file);        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));        String bookString;        List<String> bookList = new ArrayList<>();        while ((bookString = bufferedReader.readLine()) != null) {            bookList.add(bookString);        }        boolean have = false;//是否存在书籍        for (String borrowUser : bookList) {            bookinf = borrowUser.split(",");            //判断书籍是否存在            if (bookDelete.equals(bookinf[0])) {                have = true;            }            //若该书籍存在,判断书籍对应用户位是否存在用户            //若对应位用户不为“无”,则表示该书籍有人借出,则无法删除该书籍            //同时告知管理员(打印)该书籍被哪位用户借出尚未归还            if (!"无".equals(bookinf[6]) && have) {                System.out.println("该书籍尚未被用户“" + bookinf[6] + "”归还,请在其归还书籍后再进行操作!");                return;            }        }        if (have == false) {            System.out.println("无法找到该书籍,请重新确认后再进行操作!");            return;        }        for (String delBook : list) {            bookinf1 = delBook.split(",");            //找到即将删除的书籍在集合中的位置,将该部分内容从集合中删除,然后清空整个文件            if (bookDelete.equals(bookinf1[0])) {                list.remove(delBook);//在集合中删除该行                FileWriter fd = new FileWriter(file, false);//append传入false表示写入内容时将会覆盖文件中之前存在的内容                fd.write("");//执行删除操作,写入空内容覆盖之前的内容                fd.close();                break;            }        }        //重新遍历一遍更改后的集合,将内容重新写入文件内        for (String user : list) {            bookinf1 = user.split(",");            FileWriter fw = new FileWriter(file, true);//append传入true表示写入内容时将不会覆盖文件中之前存在的内容,将新的内容写在之前内容的后面            fw.write(bookinf1[0] + "," + bookinf1[1] +                    "," + bookinf1[2] + "," + bookinf1[3] +                    "," + bookinf1[4] + "," + bookinf1[5] +                    "," + bookinf1[6] + "," + bookinf1[7]);//执行重新写入内容的操作,将修改过的集合通过数组读下标后,再重新存写入文件中            fw.write(System.getProperty("line.separator"));//在段落后添加一个换行符            fw.close();        }        System.out.println("删除成功!");    }}

归还书籍ReturnBook:

package Book;import java.io.*;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Scanner;public class ReturnBook {    Scanner scanner = new Scanner(System.in);    public void returnBook(String operator) throws IOException, ParseException {        String filePath = "书籍.txt";        ReturnBook modifyFile = new ReturnBook();        File bookFile = new File("书籍.txt");        //根据书籍名称查询到需要修改的书籍数据        FileInputStream intput = new FileInputStream(bookFile);        BufferedReader reader = new BufferedReader(new InputStreamReader(intput));        String tempString = null;        List<String> list = new ArrayList<>();        while ((tempString = reader.readLine()) != null) {            list.add(tempString);        }        int flag = 0;        String[] bookinf = new String[8];        String[] bookinf1 = new String[8];        System.out.println("=======================当前已借阅书籍有=======================");        int i = 0;        for (String user : list) {            bookinf1 = user.split(",");            if (bookinf1[6].equals(operator)) {                System.out.print(" | " + bookinf1[0] + " |");                i++;                if (i % 5 == 0) {                    System.out.println("");                    System.out.println("==========================================================");                }            }        }        if (i % 5 != 0) {            System.out.println("");            System.out.println("==========================================================");        }        System.out.println("请输入要归还的书籍名称:");        String bookName = scanner.next();        for (String user : list) {            bookinf = user.split(",");            if (bookName.equals(bookinf[0]) && operator.equals(bookinf[6])) {                //判断书籍是否存在,且为本人所借出                //若属实则输出书籍完整信息                flag = 1;                System.out.println("书名:" + bookinf[0] + ",作者:" + bookinf[1] + ",价格:" + bookinf[2] + ",类型:" + bookinf[3] +                        ",出版社:" + bookinf[4] + ",是否被借出:" + bookinf[5] + ",借书人:" + bookinf[6] + ",借出日期:" + bookinf[7]);                //判断是否超时,超时需付罚金                long charge = 0;//两个时间相差的天数                Date nowDate = new Date();                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                String returnTime = sdf.format(nowDate);//获取归还时间                Date d1 = sdf.parse(bookinf[7]);//借出时间                Date d2 = sdf.parse(returnTime);//归还时间                charge = (d2.getTime() - d1.getTime()) / (24 * 60 * 60 * 1000);//天                long charge1 = (d2.getTime() - d1.getTime()) / (1000);//秒                //逾期书籍将缴纳罚金                if (charge1 <= 20) {                    System.out.println("该书籍被您借出" + charge1 + "秒,感谢您规范用书!");                } else if (charge1 > 20) {                    System.out.println("该书籍被您借出" + charge1 + "秒,您已逾期" + (charge1 - 20) + "秒,需交罚金:" + (charge1 - 20) * 5 + "元,谢谢配合!");                }//                if (charge <= 7) {//                    System.out.println("该书籍被您借出" + charge + "天,感谢您规范用书!");//                } else if (charge > 7) {//                    System.out.println("该书籍被您借出" + charge + "天,您已逾期" + (charge - 7) + "天,需交罚金:" + (charge - 7) * 5 + "元,谢谢配合!");//                }                break;            } else if (bookName.equals(bookinf[0]) && !operator.equals(bookinf[6]) && bookinf[5].equals("true")) {                //判断书籍是否存在,且为本人所借出                //若存在该书籍且被借出,但不是本人所借出,只输出该书籍基本信息                flag = 2;                System.out.println("书名:" + bookinf[0] + ",作者:" + bookinf[1] + ",价格:" + bookinf[2] +                        ",类型:" + bookinf[3] + ",出版社:" + bookinf[4] + ",是否被借出:" + bookinf[5]);                break;            } else if (bookName.equals(bookinf[0]) && bookinf[5].equals("false")) {                //判断书籍是否存在,且为本人所借出                //若存在该书籍但并未被借出,只输出该书籍基本信息                flag = 3;                System.out.println("书名:" + bookinf[0] + ",作者:" + bookinf[1] + ",价格:" + bookinf[2] +                        ",类型:" + bookinf[3] + ",出版社:" + bookinf[4] + ",是否被借出:" + bookinf[5]);                break;            }        }        if (flag == 0) {            System.out.println("没有查找到该书籍,请重新确认后再进行查找!");        } else if (flag == 2) {            System.out.println("该书不是由您所借出,请查证后再输入归还的书籍!");        } else if (flag == 3) {            System.out.println("该书并未被借出,请查证后再输入归还的书籍!");        }        //修改书籍数据后,重新写入文件        else if (flag == 1) {            if (bookName.equals(bookinf[0]) && bookinf[5].equals("true") && operator.equals(bookinf[6])) {                modifyFile.writeFile(filePath, modifyFile.readFileContent(bookinf, filePath, "true", "false"));                // 修改文件中借阅状态                modifyFile.writeFile(filePath, modifyFile.readFileContent(bookinf, filePath, operator, "无"));                modifyFile.writeFile(filePath, modifyFile.readFileContent(bookinf, filePath, bookinf[7], "null"));                System.out.println("归还成功!");                //写日志                Date nowDate = new Date();                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                String returnTime = sdf.format(nowDate);                File file = new File("日志.txt");                FileWriter fw = new FileWriter(file, true);                fw.write(returnTime + "  " + operator + "归还了图书:" + bookinf[0]);                fw.write(System.getProperty("line.separator"));//在段落后添加一个换行符                fw.close();                return;            }        }    }    // 读文件    public String readFileContent(String[] bookinf, String filePath, String oldString, String newString) {        Scanner sc = new Scanner(System.in);        BufferedReader br = null;        String line = null;        StringBuffer bufAll = new StringBuffer();// 保存修改过后的所有内容        try {            br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));//            System.out.println("请确认您的用户名:");//            String username = sc.next();            while ((line = br.readLine()) != null) {                StringBuffer buf = new StringBuffer();                // 修改内容核心代码                String[] bookinf2 = line.split(",");                if (bookinf2[0].equals(bookinf[0])) {//判断条件根据自己的要求修改                    buf.append(line);                    int indexOf = line.indexOf(oldString);                    buf.replace(indexOf, indexOf + oldString.length(), newString);// 修改内容                    buf.append(System.getProperty("line.separator"));// 添加换行                    bufAll.append(buf);                } else {                    buf.append(line);                    buf.append(System.getProperty("line.separator"));                    bufAll.append(buf);                }            }        } catch (Exception e) {            e.printStackTrace();        } finally {            if (br != null) {                try {                    br.close();                } catch (Exception e) {                    br = null;                }            }        }        return bufAll.toString();    }    // 写文件    public boolean writeFile(String filePath, String content) {        BufferedWriter bw = null;        try {            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"));            bw.write(content);            bw.flush();        } catch (Exception e) {            e.printStackTrace();            return false;        } finally {            if (bw != null) {                try {                    bw.close();                } catch (IOException e) {                    bw = null;                }            }        }        return true;    }}

查询书籍FindBook:

package Book;import java.io.*;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Scanner;public class FindBook {    Scanner scanner = new Scanner(System.in);    File bookFile = new File("书籍.txt");    public void findBook(String operator) throws IOException {        FileInputStream intput = new FileInputStream(bookFile);        BufferedReader reader = new BufferedReader(new InputStreamReader(intput));        String tempString = null;//        int line = 1;        List<String> list = new ArrayList<>();//        System.out.println("书籍 | 作者 | 价格 | 类型 | 出版社 | 是否被借出");        while ((tempString = reader.readLine()) != null) {            list.add(tempString);//            System.out.println(tempString);//            line++;        }        boolean flag = false;        String[] bookinf = new String[8];        System.out.println("=========================当前书籍有=========================");        int i = 0;        for (String user : list) {            bookinf = user.split(",");            System.out.print(" | " + bookinf[0] + " 是否被借出:" + bookinf[5] + " |");            i++;            if (i % 2 == 0) {                System.out.println("");                System.out.println("==========================================================");            }        }        if (i % 2 != 0) {            System.out.println("");            System.out.println("==========================================================");        }        System.out.println("请输入要查看详细信息的书籍名称:");        String bookName = scanner.next();        for (String user : list) {            bookinf = user.split(",");            if (bookName.equals(bookinf[0])) { //判断书籍是否存在                flag = true;                System.out.println("书名:" + bookinf[0] + ",作者:" + bookinf[1] + ",价格:" + bookinf[2] +                        ",类型:" + bookinf[3] + ",出版社:" + bookinf[4] + ",是否被借出:" + bookinf[5]);                //写日志                Date nowDate = new Date();                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                String findTime = sdf.format(nowDate);                File file = new File("日志.txt");                FileWriter fw = new FileWriter(file, true);                fw.write(findTime + "  " + operator + "查询了图书:" + bookinf[0]);                fw.write(System.getProperty("line.separator"));//在段落后添加一个换行符                fw.close();                break;            }        }        if (flag == false) {            System.out.println("没有查找到该书籍,请重新确认后再进行查找!");        }    }    public void adminFindBook() throws IOException {        FileInputStream intput = new FileInputStream(bookFile);        BufferedReader reader = new BufferedReader(new InputStreamReader(intput));        String tempString = null;        List<String> list = new ArrayList<>();        while ((tempString = reader.readLine()) != null) {            list.add(tempString);//            System.out.println(tempString);        }        String[] bookinf = new String[8];        System.out.println("=========================当前书籍有=========================");        int i = 0;        for (String user : list) {            bookinf = user.split(",");            System.out.print(" | " + bookinf[0] + " |");            i++;            if (i % 5 == 0) {                System.out.println("");                System.out.println("==========================================================");            }        }        System.out.println("");        System.out.println("==========================================================");        System.out.println("请输入要查看详细信息的书籍名称:");        String bookName = scanner.next();        boolean flag = false;        for (String user : list) {            bookinf = user.split(",");            if (bookName.equals(bookinf[0])) { //判断书籍是否存在                flag = true;                System.out.println("书名:" + bookinf[0] + ",作者:" + bookinf[1] + ",价格:" + bookinf[2] + ",类型:" + bookinf[3] +                        ",出版社:" + bookinf[4] + ",是否被借出:" + bookinf[5] + ",借书人:" + bookinf[6] + ",借出日期:" + bookinf[7]);                break;            }        }        if (flag == false) {            System.out.println("没有查找到该书籍,请重新确认后再进行查找!");        }    }}

用户界面User:

package User;import Book.BorrowBook;import Book.FindBook;import Book.ReturnBook;import java.io.*;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Scanner;public class User extends Person {    //用户属性    private long Uphone;    private String Upassword;    public User() {    }    public User(String name, String sex, int age, long Uphone, String Upassword) {        super(name, sex, age);        this.Uphone = Uphone;        this.Upassword = Upassword;    }    public long getUphone() {        return Uphone;    }    public void setUphone(int uphone) {        Uphone = uphone;    }    public String getUpassword() {        return Upassword;    }    public void setUpassword(String upassword) {        Upassword = upassword;    }    public String toString() {        return name + "," + Upassword + "," + sex + "," + age + "," + Uphone;    }    public void operation(String[] userinf, String operator) throws IOException, ParseException {        File bookFile = new File("书籍.txt");        FindBook fb = new FindBook();        while (true) {            System.out.println("===============普通用户操作界面===============");            System.out.println("1.查询书籍 2.借阅书籍 3.归还书籍 4.修改密码 5.返回");            Scanner sc = new Scanner(System.in);            int j = sc.nextInt();            if (j < 1 || j > 5) {                System.out.println("到底能不能行?能不能看明白了再输!");            } else if (j == 5) {                return;            } else if (j == 1) {//查询书籍                fb.findBook(operator);            } else if (j == 2) {//借阅书籍                BorrowBook bb = new BorrowBook();                bb.borrowBook(operator);            } else if (j == 3) {//归还书籍                ReturnBook gbb = new ReturnBook();                gbb.returnBook(operator);            } else if (j == 4) {//修改密码                String filePath = "用户信息.txt";                User modifyFile = new User();                System.out.println("请输入原密码:");                String oldString = sc.next();                //如果输入的原密码不正确,无法进行修改,如果正确,才能进行修改                if (oldString.equals(userinf[1])) {                    System.out.println("请输入新密码:");                    String newString = sc.next();                    boolean result = modifyFile.writeFile(filePath, modifyFile.readFileContent(userinf, filePath, oldString, newString));// 修改文件中密码//            如果修改结果为true,进行修改成功提示,否则提示修改失败                    if (result == true) {                        System.out.println("修改成功,请重新登录!");                        //写日志                        Date nowDate = new Date();                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                        String returnTime = sdf.format(nowDate);                        File file = new File("日志.txt");                        FileWriter fw = new FileWriter(file, true);                        fw.write(returnTime + "  " + operator + "修改了密码");                        fw.write(System.getProperty("line.separator"));//在段落后添加一个换行符                        fw.close();                        return;                    } else {                        System.out.println("修改错误,请检查后重新修改!");                    }                } else {                    System.out.println("输入错误,请检查后重新进行修改!");                }            }        }    }    // 读文件    public String readFileContent(String[] userinf, String filePath, String oldString, String newString) {        Scanner sc = new Scanner(System.in);        BufferedReader br = null;        String line = null;        StringBuffer bufAll = new StringBuffer();// 保存修改过后的所有内容        try {            br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));            while ((line = br.readLine()) != null) {                StringBuffer buf = new StringBuffer();                // 修改内容核心代码                String[] userinf2 = line.split(",");                if (userinf2[0].equals(userinf[0])) {//判断条件根据自己的要求修改                    buf.append(line);                    int indexOf = line.indexOf(oldString);                    buf.replace(indexOf, indexOf + oldString.length(), newString);// 修改内容                    buf.append(System.getProperty("line.separator"));// 添加换行                    bufAll.append(buf);                } else {                    buf.append(line);                    buf.append(System.getProperty("line.separator"));                    bufAll.append(buf);                }            }        } catch (Exception e) {            e.printStackTrace();        } finally {            if (br != null) {                try {                    br.close();                } catch (Exception e) {                    br = null;                }            }        }        return bufAll.toString();    }    // 写文件    public boolean writeFile(String filePath, String content) {        BufferedWriter bw = null;        try {            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"));            bw.write(content);            bw.flush();        } catch (Exception e) {            e.printStackTrace();            return false;        } finally {            if (bw != null) {                try {                    bw.close();                } catch (IOException e) {                    bw = null;                }            }        }        return true;    }}

管理员操作界面Admin:

package User;import Book.AddBook;import Book.DeleteBook;import Book.FindBook;import java.io.*;import java.util.Scanner;public class Admin {    public Admin() {    }    public void admin() throws IOException {        File adminBook = new File("书籍.txt");        File adminUser = new File("用户信息.txt");        FindBook fb = new FindBook();        Scanner scanner = new Scanner(System.in);        while (true) {            System.out.println("===============图书管理员操作界面===============");            System.out.println("1.查询书籍 2.添加书籍 3.删除书籍 4.增/删用户 5.查看日志 6.返回");            int choice = scanner.nextInt();            if (choice < 1 || choice > 6) {                System.out.println("到底能不能行?能不能看明白了再输!");            } else if (choice == 6) {                return;            } else if (choice == 1) {                //查询书籍                fb.adminFindBook();            } else if (choice == 2) {                //添加书籍                AddBook ab = new AddBook();                ab.addBook();            } else if (choice == 3) {                //删除书籍                DeleteBook db = new DeleteBook();                db.deleteBook();            } else if (choice == 4) {                //增删用户                System.out.println("==========增/删用户==========");                System.out.println("1.增加用户 2.删除用户 3.返回");                int decision = scanner.nextInt();                if (decision == 3) {                    //返回                    break;                } else if (decision == 1) {                    //增加用户                    AddUser au = new AddUser();                    au.addUser();                } else if (decision == 2) {                    //删除用户                    DeleteUser du = new DeleteUser();                    du.deleteUser();                }            } else if (choice == 5) {                //查看日志                File file = new File("日志.txt");                FileInputStream intput = new FileInputStream(file);                BufferedReader reader = new BufferedReader(new InputStreamReader(intput));                String tempString = null;                System.out.println("-----------------用户操作日志-----------------");                while ((tempString = reader.readLine()) != null) {                    System.out.println(tempString);                    System.out.println("--------------------------------------------");                }                while (true) {                    System.out.println("查看完毕,是否清空日志?");                    System.out.println("1.是     2.否");                    int choice1 = scanner.nextInt();                    if (choice1 == 1) {                        FileWriter fw = new FileWriter(file, false);                        fw.write("");                        fw.close();                        break;                    } else if (choice1 == 2) {                        break;                    } else if (choice1 != 1 && choice1 != 2) {                        System.out.println("请认真核对后再输入!");                    }                }            }        }    }}

增加用户AddUser:

package User;import java.io.*;import java.util.ArrayList;import java.util.List;import java.util.Scanner;public class AddUser {    public void addUser() throws IOException {        Scanner sc = new Scanner(System.in);        File file = new File("用户信息.txt");        System.out.println("请输入添加的用户名:");        String addName = sc.next();        //查找是否有同名用户        FileInputStream intput = new FileInputStream(file);        BufferedReader reader = new BufferedReader(new InputStreamReader(intput));        String tempString;        List<String> list = new ArrayList<>();        while ((tempString = reader.readLine()) != null) {            list.add(tempString);        }        String[] userinf = new String[5];        boolean flag = false;        for (String user : list) {            userinf = user.split(",");            if (addName.equals(userinf[0])) { //判断用户名是否存在                flag = true;                System.out.println("该用户名已存在,请让其重新拟取名称");                break;            }        }        if (flag == false) {            System.out.println("请输入密码:");            String password = sc.next();            String sex;            while (true) {                System.out.println("请输入用户的性别:");                sex = sc.next();                if (sex.equals("男") || sex.equals("女")) {                    break;                } else {                    System.out.println("请输入正确的性别!");                }            }            System.out.println("请输入用户的年龄:");            int age = sc.nextInt();            if (age < 10) {                System.out.println("该用户的年龄太小啦!请让家长使用账号帮他(她)借阅书籍!");                return;            }            long phone;            while (true) {                System.out.println("请输入该用户的电话号码:");                phone = sc.nextInt();                if (phone < 0) {                    System.out.println("请输入正确的电话号码!");                } else {                    break;                }            }            User u = new User(addName, sex, age, phone, password);            file.createNewFile();            FileWriter fw = new FileWriter(file, true);            fw.write(u.toString());            fw.write(System.getProperty("line.separator"));//在段落后添加一个换行符            fw.close();            System.out.println("成功添加用户:" + addName);            return;        }    }}

删除用户DeleteUser:

package User;import java.io.*;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Scanner;public class DeleteUser {    private String userDelete;    String[] userinf = new String[5];    String[] userinf1 = new String[5];    String[] userinf2 = new String[5];    public void deleteUser() throws IOException {        File file = new File("用户信息.txt");        FileInputStream intput = new FileInputStream(file);        BufferedReader reader = new BufferedReader(new InputStreamReader(intput));        Scanner scanner = new Scanner(System.in);        String tempString;        List<String> list = new ArrayList<>();        while ((tempString = reader.readLine()) != null) {            list.add(tempString);        }        System.out.println("==========当前用户有==========");        for (String user : list) {            userinf = user.split(",");            System.out.print(userinf[0] + " ");        }        System.out.println("");        System.out.println("请输入要删除信息的用户名:");        userDelete = scanner.next();        //查询该用户是否有未归还的书籍,如果存在未归还的书籍,将不能删除该用户的信息        boolean have = false;        String[] bookinf = new String[8];        File bookFile = new File("书籍.txt");        FileInputStream inputStream = new FileInputStream(bookFile);        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));        String bookString;        List<String> bookList = new ArrayList<>();        while ((bookString = bufferedReader.readLine()) != null) {            bookList.add(bookString);        }        for (String borrowUser : bookList) {            bookinf = borrowUser.split(",");            if (userDelete.equals(bookinf[6])) {                have = true;                System.out.println("该用户还有书籍尚未归还,请在其归还书籍后再进行删除!");                return;            }        }        if (have == false) {            boolean flag = false;            for (String user : list) {                userinf1 = user.split(",");                if (userDelete.equals(userinf1[0])) { //判断用户名是否存在                    flag = true;                    list.remove(user);                    FileWriter fd = new FileWriter(file, false);                    fd.write("");                    fd.close();                    break;                }            }            if (flag == true) {                for (String user : list) {                    userinf2 = user.split(",");                    FileWriter fw = new FileWriter(file, true);                    fw.write(userinf2[0] + "," + userinf2[1] + "," + userinf2[2] + "," + userinf2[3] + "," + userinf2[4]);                    fw.write(System.getProperty("line.separator"));//在段落后添加一个换行符                    fw.close();//                return;                }                System.out.println("删除成功!");            } else {                System.out.println("无法找到该用户,请重新确认后再进行操作!");                return;            }        }    }    public static void main(String[] args) throws IOException {        DeleteUser du = new DeleteUser();        du.deleteUser();    }}

最后是运行的主函数:

public static void main(String[] args) throws IOException, ParseException {        Library library = new Library();        library.Interface();    }

整个项目完成之后的包和类如下所示:

书籍和用户信息中之前添加过的信息如下:

书籍信息:

用户信息:

五、总结

该项目是我学Java以来自己制作的功能最为复杂,设计内容最丰富的项目,同时也是耗费我时间最久的项目,项目中还有很多地方的代码是可以继续优化的,而且还有很多可以增加用户体验的功能是可以再添加的。整个项目的制作过程也是我查缺补漏的一个过程,将我之前学习的比较薄弱的部分给进行了增强,同时也将一些之前学的扎实的部分进行了加固。

到此这篇关于Java实战之基于I/O流设计的图书馆管理系统的文章就介绍到这了,更多相关java图书馆管理系统内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

看了哪些风景,遇到哪些人。尽管同学说,

Java实战之基于I/O流设计的图书管理系统

相关文章:

你感兴趣的文章:

标签云: