基于文件的成绩管理系统

一 、算法思路

1、提供一个操作选项功能,根据相应的选项进行操作;

2、对于文件的操作,存在以下几个:

1)创建一个文件对象

2)判断文件是否存在

3)对于不存在的文件进行创建

4)以文件流读取文件内容

5)将内容写入到文件中

6)获取指定目录下的文件列表

3、对于学生成绩的添加,根据选项提示,输入相应的信息,后台获取到相应的信息后,将以以下形式组合成字符串“班级$学号$姓名$课程名称$份数”,将每条记录保存(追加)到文件中,一条记录在文件中存储为一行

4、学生成绩查找,输入班级名、学号、在后台将学生成绩文件里面的内容读取到内存中,循环处理没条记录,每条记录像上面提到的是以个字符串保存,我们只需要在该字符串中查找字符是否存在对应的字符就能定位该学生对应课程的成绩,匹配成功,对字符串进行解析,然后打印出相应的信息;

5、修改学生成绩,输入学号、课程和修改后的份数,在后台将学生成绩文件里面的内容读取到内存中,循环处理没条记录,每条记录像上面提到的是以个字符串保存,我们只需要在该字符串中查找字符是否存在就能定位该学生对应课程的成绩。我们用List来保存新的学生成绩,没有匹配成功的记录,直接放到list中,匹配成功的,替换新的成绩后,将替换后的字符串加到list中,遍历完之前的学生成绩内容后,将list中的内容写到(覆盖)学生成绩文件中,及完成学生成绩修改操作;

6、复制班级成绩到文件,输入班级名称,在后台将学生成绩文件里面的内容读取到内存中,根据上面提到的匹配方式,提取出对应班级的成绩,加到list中,循环完后,根据班级名称创建“班级名.csv”文件,将list中的内容写到(覆盖)该文件中,操作成功;

7、删除班级成绩,输入班级名称,在班级成绩文件目录下,先判断对应班级成绩文件是否存在,不存在不做操作,存在就删除对应文件,操作成功;

8、备份学生成绩,将学生成绩文件(main.db)文件中的内容读取出来放到list中,然后根据输入的保存后的文件名,创建新文件,将list中的内容写到(覆盖)新文件中,备份成功;

9恢复学生成绩,输入要恢复的备份文件,后台读取要恢复的备份文件内容到内存放到list中,然后将list中的内容覆盖到main.db文件中,操作成功。

二 、FileUtil

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 操作文件 实现对文件的创建、读、写、删除等操作
 * 学生成绩的添加、查找、修改 是将文件内容读取到内存list中,进行操作,完成后,将内容写回到文件中
 * @author Administrator
 *
 */
public class FileUtil {
	private static final String mainFileName = "main.db";
	/**
	 * 添加学生成绩 保存到文件
	 * @param content
	 * @return
	 */
	public static boolean saveFileContent(String content){
		FileWriter writer = null;
		try {
			String path = System.getProperty("user.dir");//获取当前路径
			String fileName = path+"/"+mainFileName;//学生成绩文件(主文件)
			File file = new File(fileName);
			if(!file.exists())//判断该文件是否存在
				file.createNewFile();//不存在新建一个空文件
			writer = new FileWriter(fileName, true);
			writer.write(content+"\n");//学生成绩写入文件

		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}finally{
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		return true;
	}
	/**
	 * 根据班级查询
	 * @param className
	 * @return
	 */
	public static List<Student> queryByClassName(String className){
		BufferedReader reader = null;
		List<Student> list = new ArrayList<Student>();
		try{
			String path = System.getProperty("user.dir");
			String fileName = path+"/"+mainFileName;
			File file = new File(fileName);
			 reader = new BufferedReader(new FileReader(file));
	         String tempString = null;
	         // 一次读入一行,直到读入null为文件结束
	         while ((tempString = reader.readLine()) != null) {
	             if(!"".equals(tempString)){
		             Student student = StringToStudent(tempString);  //将学生成绩字符串转换成学生对象
		             if(className.equals(student.getClassName())) //如果班级与输入的班级一致,就将学生信息添加到list中
		            	 list.add(student);
	             }
	         }
		  } catch (IOException e) {
	          e.printStackTrace();
	      } finally {
	          if (reader != null) {
	              try {
	                  reader.close();
	              } catch (IOException e1) {
	              }
	          }
	      }

		return list;
	}
	/**
	 * 根据课程查询
	 * @param courseName
	 * @return
	 */
	public static List<Student> queryByCourseName(String courseName){
		BufferedReader reader = null;
		List<Student> list = new ArrayList<Student>();
		try{
			String path = System.getProperty("user.dir");
			String fileName = path+"/"+mainFileName;
			File file = new File(fileName);
			 reader = new BufferedReader(new FileReader(file));
	         String tempString = null;
	         // 一次读入一行,直到读入null为文件结束
	         while ((tempString = reader.readLine()) != null) {
	             if(!"".equals(tempString)){
		             Student student = StringToStudent(tempString); //将学生成绩字符串转换成学生对象
		             if(courseName.equals(student.getCourseName()))//如果课程与输入的课程一致,就将学生信息添加到list中
		            	 list.add(student);
	             }
	         }
		  } catch (IOException e) {
	          e.printStackTrace();
	      } finally {
	          if (reader != null) {
	              try {
	                  reader.close();
	              } catch (IOException e1) {
	              }
	          }
	      }

		return list;
	}
	/**
	 * 根据学号查询
	 * @param stuNo
	 * @return
	 */
	public static List<Student> queryByStuNo(String stuNo){
		BufferedReader reader = null;
		List<Student> list = new ArrayList<Student>();
		try{
			String path = System.getProperty("user.dir");
			String fileName = path+"/"+mainFileName;
			File file = new File(fileName);
			 reader = new BufferedReader(new FileReader(file));
	         String tempString = null;
	         // 一次读入一行,直到读入null为文件结束
	         while ((tempString = reader.readLine()) != null) {
	             if(!"".equals(tempString)){
		             Student student = StringToStudent(tempString);//将学生成绩字符串转换成学生对象
		             if(stuNo.equals(student.getStuNo())){//如果学号与输入的学号一致,就将学生信息添加到list中
		            	 list.add(student);
		             }
	             }
	         }
		  } catch (IOException e) {
	          e.printStackTrace();
	      } finally {
	          if (reader != null) {
	              try {
	                  reader.close();
	              } catch (IOException e1) {
	              }
	          }
	      }

		return list;
	}
	/**
	 * 修改学生成绩
	 * @param stuNo
	 * @param score
	 * @return
	 */
	public static boolean updateScore(String stuNo,String course,String score){
		BufferedReader reader = null;
		List<String> list = new ArrayList<String>();
		try{
			String path = System.getProperty("user.dir");
			String fileName = path+"/"+mainFileName;
			File file = new File(fileName);
			 reader = new BufferedReader(new FileReader(file));
	         String tempString = null;
	         // 一次读入一行,直到读入null为文件结束
	         while ((tempString = reader.readLine()) != null) {
	             // 显示行号
	             if(!"".equals(tempString)){
	            	//在学生成绩字符串中匹配学号和课程 如果都匹配成功就进行修改操作
		             if(tempString.indexOf("$"+stuNo+"$")!=-1&&tempString.indexOf("$"+course+"$")!=-1){
		            	System.out.println(tempString);
		            	Student stu = StringToStudent(tempString);
		            	StringBuffer stuInfoBuffer = new StringBuffer();
		         		stuInfoBuffer.append(stu.getClassName()+"$");
		         		stuInfoBuffer.append(stu.getStuNo()+"$");
		         		stuInfoBuffer.append(stu.getName()+"$");
		         		stuInfoBuffer.append(stu.getCourseName()+"$");
		         		stuInfoBuffer.append(score);//替换成新的成绩
		         		String result = stuInfoBuffer.toString();
		         		list.add(result);
		             }else{
		            	list.add(tempString);
		             }
	             }
	         }
	         
	         
	        FileWriter writer = null;
	 		try {
	 			writer = new FileWriter(fileName, false);
	 			for(String content:list)//将修改后的学生成绩 覆盖之前的学生成绩(覆盖之前的main.db中的内容)
	 				writer.write(content+"\n");

	 		} catch (IOException e) {
	 			e.printStackTrace();
	 			return false;
	 		}finally{
	 			try {
	 				writer.close();
	 			} catch (IOException e) {
	 				e.printStackTrace();
	 			}
	 			
	 		}
		  } catch (IOException e) {
	          e.printStackTrace();
	      } finally {
	          if (reader != null) {
	              try {
	                  reader.close();
	              } catch (IOException e1) {
	              }
	          }
	      }
		System.out.println("更新成功!");
		return true;
	}
	/**
	 * 字符串转换成Student对象
	 * @param stustr
	 * @return
	 */
	public static Student StringToStudent(String stustr){
		 Student student  = new Student();
		 String[] studentInfo = stustr.split("\\$");
		 student.className = studentInfo[0];
		 student.stuNo = studentInfo[1];
		 student.name = studentInfo[2];
		 student.courseName = studentInfo[3];
		 student.score = studentInfo[4];
		 return student;
	}
	/**
	 * 复制班级成绩到文件
	 * @param className
	 * @return
	 */
	public static List<String> copyScoreToFile(String className){
		BufferedReader reader = null;
		List<String> list = new ArrayList<String>();
		List<String> list1 = new ArrayList<String>();
		String path = System.getProperty("user.dir");
		try{
			String fileName = path+"/"+mainFileName;
			File file = new File(fileName);
			 reader = new BufferedReader(new FileReader(file));
	         String tempString = null;
	         // 一次读入一行,直到读入null为文件结束
	         while ((tempString = reader.readLine()) != null) {
	             // 显示行号
	             if(!"".equals(tempString)){
		             if(tempString.indexOf(className+"$")!=-1){
		         		list.add(tempString);
		             }
	             }
	         }
	         
	         
		  } catch (IOException e) {
	          e.printStackTrace();
	      } finally {
	          if (reader != null) {
	              try {
	                  reader.close();
	              } catch (IOException e1) {
	              }
	          }
	      }
		// 复制到班级文件
		if(list.size()!=0){
	        FileWriter writer = null;
	 		try {
				String fileName = path+"/data/"+className+".csv";
				File file = new File(fileName);
				if(!file.exists())
					file.createNewFile();
	 			writer = new FileWriter(fileName, false);
	 			writer.write("班级,学号,姓名,课程,分数\n");
	 			for(String content:list)
	 				writer.write(content.replace("$", ",")+"\n");
	
	 		} catch (IOException e) {
	 			e.printStackTrace();
	 		}finally{
	 			try {
	 				writer.close();
	 			} catch (IOException e) {
	 				e.printStackTrace();
	 			}
	 		}
		}
 		System.out.println("复制成功!");
		printClassFile();
        return list1;
	}
	/**
	 * 删除班级成绩文件
	 * @param className
	 * @return
	 */
	public static boolean deleteClassFile(String className){
			String path = System.getProperty("user.dir");
			String fileName = path+"/data/"+className+".csv";
			File file1 = new File(fileName);
			if(file1.exists())
				file1.delete();
			System.out.println("删除成功!");
			printClassFile();
		return false;
	}
	/**
	 * 备份学生成绩
	 * @param mainBackup
	 * @return
	 */
	public static boolean backUpMainFile(String mainBackup){
		BufferedReader reader = null;
		List<String> list = new ArrayList<String>();
		List<String> list1 = new ArrayList<String>();
		String path = System.getProperty("user.dir");
		try{
			String fileName = path+"/"+mainFileName;
			File file = new File(fileName);
			 reader = new BufferedReader(new FileReader(file));
	         String tempString = null;
	         // 一次读入一行,直到读入null为文件结束
	         while ((tempString = reader.readLine()) != null) {
	             if(!"".equals(tempString)){
		         		list.add(tempString);
	             }
	         }
	         
	         
		  } catch (IOException e) {
	          e.printStackTrace();
	      } finally {
	          if (reader != null) {
	              try {
	                  reader.close();
	              } catch (IOException e1) {
	              }
	          }
	      }
		// 备份
		if(list.size()!=0){
	        FileWriter writer = null;
	 		try {
				String fileName = path+"/backup/"+mainBackup;
				File file = new File(fileName);
				File file1 = new File(path+"/backup/");
				if(!file1.exists()){
					file1.mkdirs();
				}
				if(!file.exists())
					file.createNewFile();
	 			writer = new FileWriter(fileName, false);
	 			for(String content:list)
	 				writer.write(content+"\n");
	
	 		} catch (IOException e) {
	 			e.printStackTrace();
	 		}finally{
	 			try {
	 				writer.close();
	 			} catch (IOException e) {
	 				e.printStackTrace();
	 			}
	 		}
		}
 		System.out.println("备份成功!");
 		printClassFile("");
		return false;
	}
	/**
	 * 备份学生成绩
	 * @param mainBackup
	 * @return
	 */
	public static boolean reserve(String mainBackup){
		BufferedReader reader = null;
		List<String> list = new ArrayList<String>();
		List<String> list1 = new ArrayList<String>();
		String path = System.getProperty("user.dir");
		try{
			
			String fileName = path+"/backup/"+mainBackup;
			File file = new File(fileName);
			if(!file.exists()){
				System.out.println("备份文件不存在,请确认备份文件后,重新操作!");
				return false;
			}
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			// 一次读入一行,直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				if(!"".equals(tempString)){
					list.add(tempString);
				}
			}
			
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		// 备份
		if(list.size()!=0){
			FileWriter writer = null;
			try {
				String fileName = path+"/"+mainFileName;
				File file = new File(fileName);
				if(!file.exists())
					file.createNewFile();
				writer = new FileWriter(fileName, false);
				for(String content:list)
					writer.write(content+"\n");
				
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println("恢复成功!");
		return true;
	}
	public static void printClassFile(String...fileName){
		String path = System.getProperty("user.dir");
		if(fileName.length!=0){
			path = path+"/backup/";
			System.out.println("备份文件如下:============================");
		}else{
			path = path+"/data/";
			System.out.println("班级成绩文件如下:============================");
		}
		File file = new File(path);  
        if (file.isDirectory()) {  
            File[] dirFile = file.listFiles();  
            for (File f : dirFile) {  
            	if(fileName.length==0){
                    if (f.getName().endsWith(".csv"))  {
                        System.out.println(f.getAbsolutePath());  
                    }
            	}else{
            		 System.out.println(f.getAbsolutePath());  
            	}
            }  
        }  
	}
}

三 、Student

public class Student {
	public String name;
	
	public String className;
	
	public String stuNo;
	
	public String courseName;
	
	public String score;

	public String getName() {
		return name;
	}

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

	public String getClassName() {
		return className;
	}

	public void setClassName(String className) {
		this.className = className;
	}

	public String getStuNo() {
		return stuNo;
	}

	public void setStuNo(String stuNo) {
		this.stuNo = stuNo;
	}

	public String getCourseName() {
		return courseName;
	}

	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}

	public String getScore() {
		return score;
	}

	public void setScore(String score) {
		this.score = score;
	}
	
	
}

四 、score

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class score {
	public static void main(String[] args) {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try {
			
			int chooseNum = putChooseNum();
			while(chooseNum!=0){
				switch(chooseNum){
				case 1:
					System.out.println("===================学生成绩录入========================");
					Student stu = new Student();
					stu.className = putMessage("录入班级名称:");
					stu.stuNo = putMessage("录入学号:");
					stu.name = putMessage("录入姓名:");
					stu.courseName = putMessage("录入课程名:");
					stu.score = putMessage("录入分数:");
					addStuScore(stu);
					break;
				case 2:
					String className = putMessage("输入班级名称:");
					List<Student> list = FileUtil.queryByClassName(className);
					System.out.println("班级	学号	姓名	课程		分数");
					System.out.println("=================================================================");
					for(Student student:list){
						System.out.println(student.getClassName()+"	"+student.getStuNo()+"	"+student.getName()+"	"+student.getCourseName()+"	"+student.getScore()+"	");
						System.out.println("-----------------------------------------------------------------");
					}
					break;
				case 3:
					String courseName = putMessage("输入课程名称:");
					List<Student> list1 = FileUtil.queryByCourseName(courseName);
					System.out.println("班级	学号	姓名	课程		分数");
					System.out.println("=================================================================");
					for(Student student:list1){
						System.out.println(student.getClassName()+"	"+student.getStuNo()+"	"+student.getName()+"	"+student.getCourseName()+"	"+student.getScore()+"	");
						System.out.println("-----------------------------------------------------------------");
					}
					break;
				case 4:
					String  stuNo= putMessage("输入学号:");
					List<Student> list2 = FileUtil.queryByStuNo(stuNo);
					System.out.println("班级	学号	姓名	课程		分数");
					System.out.println("=================================================================");
					for(Student student:list2){
						System.out.println(student.getClassName()+"	"+student.getStuNo()+"	"+student.getName()+"	"+student.getCourseName()+"	"+student.getScore()+"	");
						System.out.println("-----------------------------------------------------------------");
					}
					break;
				case 5:
					String  stuNo1= putMessage("输入学号:");
					String  course= putMessage("输入课程名称:");
					String  score1 = putMessage("成绩修改为:");
					FileUtil.updateScore(stuNo1,course,score1);
					break;
				case 6:
					String className1 = putMessage("输入班级名称:");
					FileUtil.copyScoreToFile(className1);
					break;
				case 7:
					FileUtil.printClassFile();
					String className2 = putMessage("输入班级名称:");
					FileUtil.deleteClassFile(className2);
					break;
				case 8:
					String backupName = putMessage("输入备份后的文件名:");
					FileUtil.backUpMainFile(backupName);
					break;
				case 9:
					FileUtil.printClassFile("");
					String backupName1 = putMessage("输入恢复备份的文件名:");
					FileUtil.reserve(backupName1);
					break;
				}
				chooseNum = putChooseNum();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 选择
	 * @return
	 */
	public static int putChooseNum(){
		int chooseNum = 0;
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			System.out.println("");
			System.out.println("****************************学生成绩管理系统***************************");
			System.out.println("*	1、添加学生成绩 ----------------------------------------------*");
			System.out.println("* 	2、按班级查询成绩---------------------------------------------*");
			System.out.println("* 	3、按课程查询成绩---------------------------------------------*");
			System.out.println("* 	4、按学号查询成绩---------------------------------------------*");
			System.out.println("* 	5、修改学生成绩-----------------------------------------------*");
			System.out.println("* 	6、复制班级成绩到文件-----------------------------------------*");
			System.out.println("* 	7、删除班级成绩文件-------------------------------------------*");
			System.out.println("* 	8、备份学生成绩-----------------------------------------------*");
			System.out.println("* 	9、恢复学生成绩-----------------------------------------------*");
			System.out.println("* 	0、退出-------------------------------------------------------*");
			System.out.println("************************************************************************");
			System.out.print("请选择操作:");
			String a = br.readLine();
			System.out.println("");
			chooseNum = Integer.parseInt(a);
		} catch (IOException e) {
			e.printStackTrace();
		} catch(Exception e){
			System.out.println("你输入编号选择!");
		}
		return chooseNum;
	}
	/**
	 * 录入信息处理
	 * @param tip
	 * @return
	 */
	public static String putMessage(String tip){
		String input = "";
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			System.out.print(tip);
			input = br.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return input;
	}
	/**
	 * 添加学生成绩
	 * @return
	 */
	public static boolean addStuScore(Student stu){
		StringBuffer stuInfoBuffer = new StringBuffer();
		stuInfoBuffer.append(stu.getClassName()+"$");
		stuInfoBuffer.append(stu.getStuNo()+"$");
		stuInfoBuffer.append(stu.getName()+"$");
		stuInfoBuffer.append(stu.getCourseName()+"$");
		stuInfoBuffer.append(stu.getScore());
		String result = stuInfoBuffer.toString();
		boolean flag = FileUtil.saveFileContent(result);
		if(flag)
			System.out.println("录入成功!");
		return false;
	}
	
}


转载于:https://my.oschina.net/fairy1674/blog/636101

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值