• java粗略版图书管理系统


    需求:编写“图书管理”程序,能支持对书的增加,删除,查看操作,并支持退出程序功能。

    每本书应包括编号,书名,价格。删除书必须输入书的编号,若输入书编号无对应的书则用提示输入有误,若有并删除且提示删除成功。

    这个程序我采用IO流去实现,用txt文件存储书籍信息。

    一、第一步:创建一个书的类Book.java

    package 图书管理程序升级版;
    
    public class Book {
        private String ID;//书的编号
        private String Name;//书名
        private String price;//书的价格
        
        
        public  Book() {
            super();
        }
        public Book(String iD, String name, String price) {
            super();
            ID = iD;
            Name = name;
            this.price = price;
        }
        
        public String getID() {
            return ID;
        }
        public void setID(String iD) {
            ID = iD;
        }
        public String getName() {
            return Name;
        }
        public void setName(String name) {
            Name = name;
        }
        public String getPrice() {
            return price;
        }
        public void setPrice(String price) {
            this.price = price;
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Book other = (Book) obj;
            if (ID == null) {
                if (other.ID != null)
                    return false;
            } else if (!ID.equals(other.ID))
                return false;
            if (Name == null) {
                if (other.Name != null)
                    return false;
            } else if (!Name.equals(other.Name))
                return false;
            if (price == null) {
                if (other.price != null)
                    return false;
            } else if (!price.equals(other.price))
                return false;
            return true;
        }
        @Override
        public String toString() {
            return "Book [ID=" + ID + ", Name=" + Name + ", price=" + price + "]";
        }
        
    
    }

    二、第二步:创建增删修改、查询功能的接口类BookDao.java

    package 图书管理程序升级版;
    /**
     * 图书馆管理程序的接口
     * @author Asus
     *
     */
    interface BookDao {
        public void addBook(Book book);//增添书籍
        
        public void findBook(String bookName);//查询书籍
        
        public boolean alterBook(String BookName,String newstr);//修改书籍内容
        
        public void cancelBook(String bookName,String ID);//删除书籍
    
    }

    三、第三步:创建接口的实现类BookDaoImpl.java

    package 图书管理程序升级版;
    
    import java.io.BufferedReader;
    
    //import static net.mindview.util.Print.print;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    
    public class BookDaoImpl implements BookDao{
        private static File file=new File("bookUser.txt");
        private static File file1=new File("temp.txt");
        static {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                System.out.println("用户创建信息文件失败");
            }
        }
        /**增添书籍
         * @param Book 书籍信息
         *     
         *  */
        public void addBook(Book book) {
            BufferedWriter bw=null;
            try {
                bw=new BufferedWriter(new FileWriter(file,true));//true代表将数据写入文件末尾处,而不是文件开始处
                bw.write("
    ");//因为文件最后一行的末尾没有回车换行符,如果不先加回车换行符,就会直接在最后一行写,不会新增一行
                bw.write(book.getID()+"-"+book.getName()+"-"+book.getPrice());
                bw.flush();
                
            } catch (IOException e) {
                
                e.printStackTrace();
            }finally{
                if(bw!=null) {
                     try {
                        bw.close();
                    } catch (IOException e) {
                        System.out.println("用户释放资源失败");
                        }
                    }
            }
            
        }
    
    /**查询书籍信息
     * @param bookName 用户要查询的书籍名称
     * 
     */
        public void findBook(String bookName) {
            BufferedReader br=null;
            try {
                br=new BufferedReader(new FileReader(file));
                String readLine = "";
                while((readLine = br.readLine()) != null){
                    String list[]=readLine.split("-");
                    if(list[1].equals(bookName)) {
                        System.out.println("ID:"+list[0]+"
    书名:"+list[1]+"
    价格:"+list[2]);
                        System.out.println("--------------------");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                if(br!=null) {
                     try {
                        br.close();
                    } catch (IOException e) {
                        System.out.println("用户释放资源失败");
                        }
                    }
            }
            
        }
    
    /**修改书籍信息
     * @param oldstr 原书籍信息
     * @param newstr 修改后的书籍信息
     * @return
     */
        public boolean alterBook(String oldName,String buffer) {
            File file=new File("bookUser.txt");
            RandomAccessFile raf=null;
            try {
                raf=new RandomAccessFile(file, "rw");
                String Line=null;
                //System.out.println(raf.length());
                
                while((Line=raf.readLine())!=null) {
                    String changeLine=new String(Line.getBytes("ISO-8859-1"), "gb2312"); //gb2312是你文本编码格式。
    
                    //查找要替换的内容
                    if(changeLine.contains(oldName)) {
                        //得到当前指针的位置,如果不是最后一行,就应该是在oldName
    后面;
                        //如果是最后一行,则就在oldName后面
                        long lastpoint=raf.getFilePointer();
                        
                        //如果是最后一行
                        if(lastpoint==raf.length()) {
                            //指针回到行首
                            raf.seek(lastpoint-changeLine.getBytes().length);
                            int currentLength=changeLine.getBytes().length;//原字符串的字节长度,1个中文字符占2字节
                            int targeLength=buffer.getBytes().length;//替换后字符串的字节长度
                            
                            //替换的字符串字节数比源字符串小
                            if(currentLength>targeLength) {
                                int tempLength=currentLength-targeLength;
                                StringBuilder sb=new StringBuilder(buffer);
                                //目的是防止修改的内容没有没全替换掉
                                
                                for(int a=0;a<tempLength;a++) {
                                    sb.append(" ");
                                }
                                raf.writeBytes(new String(sb.toString().getBytes("gb2312"), "ISO-8859-1"));
                            }else {
                                //替换的字符串字节数比源字符串大或两者相等
                                raf.writeBytes(new String(buffer.getBytes("gb2312"), "ISO-8859-1"));
                                
                            }
                        }else {//不是最后一行
                            //回到行首,减去2的原因是行末有
    ,占2字节
                            raf.seek(lastpoint-changeLine.getBytes().length-2);
                            int currentLength=changeLine.getBytes().length;//原字符串的长度
                            int targeLength=buffer.getBytes().length;//替换后字符串的长度
                            //替换的字符串字节数比源字符串小,目的是防止修改的内容没有没全替换掉
                            if(currentLength>targeLength) {
                                int tempLength=currentLength-targeLength;
                                StringBuilder sb=new StringBuilder(buffer);
                                //源字符串没替换的字符用空格代替                            
                                for(int a=0;a<tempLength;a++) {
                                    sb.append(" ");
                                }
                                
                                raf.writeBytes(new String(sb.toString().getBytes("gb2312"), "ISO-8859-1"));
                            }else {
                                //替换的字符串比源字符串大或两者相等
                                raf.writeBytes(new String(buffer.getBytes("gb2312"), "ISO-8859-1"));                            
                            }
                            
                        }
                        break;
                    }
    
                }
                
            } catch (Exception e) {            
                e.printStackTrace();
            }finally{
                if(raf!=null) {
                     try {
                        raf.close();
                    } catch (IOException e) {
                        System.out.println("用户释放资源失败");
                        }
                    }
            }
            return true;        
        }
    
    
        /**删除书籍信息
         * @param bookName 用户要删除的书籍名称
         * @param ID 用户输入该书籍的编号
         */
        public void cancelBook(String bookName,String ID) {
            boolean flag=false;
            BufferedWriter bw=null;
            BufferedReader br=null;
            StringBuilder sb=null;
            try {
                bw=new BufferedWriter(new FileWriter(file1));
                br=new BufferedReader(new FileReader(file));
                String line=null;
                sb=new StringBuilder();
                while((line=br.readLine())!=null) {
                   //要删除的那一行
                    if(line.contains(bookName)) {
                        String []data=line.split("-");//将书籍编号、书籍名、书籍价格存在数组中
                        if(!ID.equals(data[0]))
                            System.out.println("输入编号不正确"); 
                        else
                            //如果删除的书籍信息都匹配成功
                            flag=true;
                    }else {
                //不是要删除的那一行 sb.append(line).append(
    " ");//存储没有被删的书籍信息 } }
    int lastindex=sb.lastIndexOf(" ");//获取最后一行书籍信息的回车换行符索引
    sb.delete(lastindex,sb.length());//删除最后一行书籍信息的回车换行符

    //如果输入的删除信息都匹配成功,就开始删除信息 if(flag) { bw.write(sb.toString());//将字符串写进新的文件中 //重命名文件必须先关闭流 bw.close(); br.close(); if(file.delete())//重命名前必须删除同名文件 file1.renameTo(file); } }catch (Exception e) { e.printStackTrace(); }finally{ if(br!=null&bw!=null) { try { bw.close(); br.close(); } catch (IOException e) { System.out.println("用户释放资源失败"); } } } } }

    四、最后一步:测试类Test.java

    package 图书管理程序升级版;
    
    import java.util.Scanner;
    
    
    
    public class Test {
        public static void main(String args[]) {
            
            String str="y";
            Scanner sc=new Scanner(System.in);
            BookDao ud=new BookDaoImpl();
    
            //欢迎界面
            while(str.equals("y")) {
                System.out.println("----------欢迎光临-----------");
                System.out.println("1 增添书籍");
                System.out.println("2 查询书籍");
                System.out.println("3 修改书籍");
                System.out.println("4 删除书籍");
                //键盘录入选择项目
                
                System.out.println("请输入你的选项:");
                String choice=sc.nextLine();
                
                
                switch (choice) {
                case "1": {                
                    System.out.println("请输入书籍的编号:");
                    String ID=sc.nextLine();
                    System.out.println("请输入书籍名称:");
                    String name=sc.nextLine();
                    System.out.println("请输入书籍价钱:");
                    String price=sc.nextLine();
                    Book book=new Book(ID,name,price);
                    ud.addBook(book);
    
                    break;            
                }
                case "2":
                    System.out.println("请输入要查询的书籍名称:");
                    String findName=sc.nextLine();
                    ud.findBook(findName);
                    break;
                case "3":
                    StringBuffer buffer=new StringBuffer();
                    
                    System.out.println("请输入你要修改的书籍名称:");
                    String oldName=sc.nextLine();
                    ud.findBook(oldName);
                    System.out.println("修改后的书籍编号是:");
                    String new1=sc.nextLine();
                    System.out.println("修改后的书籍名称是:");
                    String new2=sc.nextLine();
                    System.out.println("修改后的书籍价格是:");
                    String new3=sc.nextLine();
                    buffer.append(new1).append("-").append(new2).append("-").append(new3);                
                    if(ud.alterBook(oldName,buffer.toString())) {
                        System.out.println("修改成功!修改后的信息是:");
                        ud.findBook(new2);
                    }
                    break;
                case "4":
                    System.out.println("请输入你要删除的书籍名称:");
                    String name=sc.nextLine();
                    System.out.println("请输入该书籍的编号:");
                    String id=sc.nextLine();
                    ud.cancelBook(name, id);
                    break;
                default:
                    System.out.println("欢迎下次光临");
                    System.exit(0);
                
             }
            System.out.println("是否继续查询:y/n");
            str=sc.nextLine();
            if(str.equals("n")) {
                System.out.println("欢迎下次光临");
                break;
            }
         }
            
        }
    
    }

    结果:

     

    小结:

    java小白,没怎么优化,代码有点长。这个程序做了差不多一周,因为卡在修改书籍那里了,修改书籍采用了RandomAccessFile(随机访问流),可以在当前文件修改内容,不用修改一次就重新创建一个新文件。接下来想跟安卓一起结合起来,做一个登录图书管理系统页面。希望可以做出来。

  • 相关阅读:
    java 多线程4: java线程的优先级
    Thread.currentThread().getName() ,对象实例.getName() 和 this.getName()区别
    go http
    go redis
    go tcp
    go 单元测试
    go 定时器
    go channel
    go goroutine
    go 错误处理
  • 原文地址:https://www.cnblogs.com/panqiaoyan/p/12730804.html
Copyright © 2020-2023  润新知