用JAVA实现对txt文件文本增删改查

package com.qiqiao.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class StudentManager {
    private static File DB = new File("students.db");
    private static Set<Student> studentList = null;

    @SuppressWarnings("unchecked")
    private static void initStudentList() {
        if (DB.exists()) {
            FileInputStream fi = null;
            ObjectInputStream oi = null;
            try {
                fi = new FileInputStream(DB);
                oi = new ObjectInputStream(fi);
                Object obj = oi.readObject();
                fi.close();
                oi.close();
                if (obj instanceof Set)
                    studentList = (Set<Student>) obj;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (studentList == null)
            studentList = new HashSet<Student>();
    }

    private static void save() {
        if (studentList == null)
            return;
        if (!DB.exists())
            try {
                DB.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        FileOutputStream fo;
        try {
            fo = new FileOutputStream(DB);
            ObjectOutputStream oo = new ObjectOutputStream(fo);
            oo.writeObject(studentList);
            fo.close();
            oo.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Student[] getStudents(int id, String name) {
        HashSet<Student> rlt = new HashSet<Student>();
        if (id != 0) {
            for (Student s : studentList) {
                if (s.id == id)
                    rlt.add(s);
            }
        } else if (name != null && !name.isEmpty()) {
            for (Student s : studentList) {
                if (s._name.equalsIgnoreCase(name))
                    rlt.add(s);
            }
        }
        return rlt.toArray(new Student[0]);
    }

    static {
        initStudentList();
    }

    static void out(Object obj) {
        System.out.println(obj);
    }

    public static void menu() {
        out("Welcome to use Student Manager!\n1-search student;\t2-add student;\t3-list all students;\nothers-exit");
        Scanner in = new Scanner(System.in);
        Student student = null;
        String input = in.nextLine();
        if (input.equals("1")) {
            Student[] students = new Student[0];
            out("please input name/id");
            String ins = in.nextLine();
            if (ins.matches("\\d+"))
                students = getStudents(Integer.parseInt(ins), null);
            else
                students = getStudents(0, ins);
            if (students.length != 0) {
                out(Arrays.toString(students).replaceAll("\\[|\\]|, ", "\n"));
                if (students.length == 1)
                    student = students[0];
                else {
                    out("please choose a student by id:\n");
                    int i = in.nextInt();
                    for (Student s : students) {
                        if (s.id == i) {
                            student = s;
                            break;
                        } else {
                            out("error");
                            menu();
                        }
                    }
                }
                out("1-set score;\t2-delete score;\t3-delete student;\tother-exit");
                int input1 = in.nextInt();
                in.nextLine();
                String course = null;
                float score = 0;
                switch (input1) {
                case 1:
                    out("please input course");
                    course = in.nextLine();
                    out("please input score");
                    score = in.nextFloat();
                    in.nextLine();
                    student.setScore(course, score);
                    break;
                case 2:
                    out("please input course");
                    course = in.nextLine();
                    student.removeScore(course);
                    break;
                case 3:
                    student.removeFrom(studentList);
                    break;
                }
            } else {
                out("NO current record!");
            }
        }
        if (input.equals("2")) {
            out("please input id");
            int id = in.nextInt();
            in.nextLine();
            out("please input name");
            String name = in.nextLine();
            out("please input class");
            String cname = in.nextLine();
            student = new Student(id, name, cname);
            if (studentList.add(student)) {
                out("create success!\n");
                String input2 = "-";
                while (!input2.isEmpty()) {
                    out("set score? \n1-yes;\t2-no");
                    input2 = in.nextLine();
                    if (input2.equals("1")) {
                        out("please input course");
                        String course = in.nextLine();
                        out("please input score");
                        float score = in.nextFloat();
                        student.setScore(course, score);
                        in.nextLine();
                    } else
                        break;
                }
            } else
                out("Error: id or student exists");
        }
        if (input.equals("3")) {
            out(studentList.toString().replaceAll("\\[|\\]|, ", "\n"));
        }
        if (input.isEmpty())
            return;
        save();
        menu();
    }

    public static void main(String[] args) {
        menu();
    }
}

class Student implements Serializable {
    public String toString() {
        return "id: "
                + id
                + "\tclass: "
                + _class
                + "\tname: "
                + _name
                + courses.toString().replaceAll("\\{|\\}|, ", "\n").replaceAll(
                        "=", ": ");
    }

    Student(int id, String _name, String _class) {
        this.id = id;
        this._class = _class;
        this._name = _name;
    }

    private static final long serialVersionUID = 1L;
    public int id = 0;

    public String _name = "";
    public String _class = "";
    HashMap<String, Float> courses = new HashMap<String, Float>();

    void setScore(String course, float score) {
        courses.put(course, score);
        System.out.println("set success!\n\n" + this);
    }

    void removeScore(String course) {
        courses.remove(course);
        System.out.println("delete success!\n\n" + this);
    };

    void removeFrom(Set<?> list) {
        list.remove(this);
        System.out.println("delete success!");
    }

    public int hashCode() {
        return 31;
    }

    public boolean equals(Object obj) {
        Student s = null;
        if (obj instanceof Student) {
            System.out.println(1);
            s = (Student) obj;
            return s.id == id
                    || (s._class.equals(_class) && s._name.equals(_name));
        }
        return false;
    }
}

class DaJiangYou {
    DaJiangYou() {
        System.out.println("I am da jiang you");
    }
}
时间: 2024-11-03 21:24:34

用JAVA实现对txt文件文本增删改查的相关文章

Java实现对xml文件的增删改查

package com.HeiBeiEDU.test2; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.junit.Test; import org.w3c.dom.*; import org.xml.sax.SAXException; import javax.xml.parser

【java】用javaSE来实现对mysql数据库的增删改查

主程序: import Bean.StudentBean;import Impl.StudentImpl; public class T7 {    public static void main(String[] args) {        StudentImpl stdimp = new StudentImpl();//        StudentBean student = new StudentBean("halala", "woman", "

SQLite帮助类SQlitehelper 实现对SQLite数据的增删改查

public class SQLiteHelper { public const string sConn = "Data Source=" + @"path"; /// <summary> /// 查询,返回object ,得到查询结果的首行首列的值,若没有首行首列返回NUll /// </summary> /// <param name="sql">查询语句</param> /// <pa

【Mysql】Java中对Mysql数据库的增删改查、Java的System类

这部分也是所谓JDBC.网站数据源的内容,把名字弄得很高深似得,实际上只是Java中对Mysql数据库的增删改查的内容.非常简单,之前写了这么多Mysql的内容,没好好总结一下,实在是不应该.今天就实现一个Java中对Mysql数据库的增删改查,随便带点Java取出当前系统的系统名与系统时间的知识,完成一个还算有点意思的小例子. 一.基本目标 首先,在Mysql数据库中有一张名为testtable的空表,id为自增列,username,class都是文本列,但是class里面都存放数字,也就是整

MyBatis学习(二)、SQL语句映射文件(2)增删改查、参数、缓存

二.SQL语句映射文件(2)增删改查.参数.缓存 2.2 select 一个select 元素非常简单.例如: Xml代码   <!-- 查询学生,根据id --> <select id="getStudent" parameterType="String" resultMap="studentResultMap"> SELECT ST.STUDENT_ID, ST.STUDENT_NAME, ST.STUDENT_SEX

文件的增删改查

有以下员工信息表 当然此表你在文件存储时可以这样表示 1 1,Alex Li,22,13651054608,IT,2013-04-01 现需要对这个员工信息文件,实现增删改查操作 可进行模糊查询,语法至少支持下面3种: select name,age from staff_table where age > 22 select  * from staff_table where dept = "IT" select  * from staff_table where enroll

java jdbc 连接mysql数据库 实现增删改查

好久没有写博文了,写个简单的东西热热身,分享给大家. jdbc相信大家都不陌生,只要是个搞java的,最初接触j2ee的时候都是要学习这么个东西的,谁叫程序得和数据库打交道呢!而jdbc就是和数据库打交道非常基础的一个知识,也是比较接近底层的,在实际的工作中大家用得更多的其实还是比较成熟的框架,例如Hibernate.Mybatis. 但是作为这些成熟框架的底层的jdbc却也是我们应该去掌握的,只有了解了jdbc的增删改查,这样在以后如果有兴趣去研究Hibernate或者Mybatis的源代码的

java H2数据库使用并实现增删改查功能

原文:java H2数据库使用并实现增删改查功能 代码下载地址:http://www.zuidaima.com/share/1550463278058496.htm package com.zuidaima.h2sql.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.St

Java通过JDBC进行简单的增删改查(以MySQL为例)

Java通过JDBC进行简单的增删改查(以MySQL为例) 目录: 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操作   (1)定义记录的类(可选) (2)连接的获取 (3)insert (4)update (5)select (6)delete 四.测试 五.代码分析 六.思考问题 前言:什么是JDBC 维基百科的简介: Java 数据库连接,(Java Database Connectivity,