studentdaofromtextfile.java

来自「这是一个很好的考试系统的源码」· Java 代码 · 共 51 行

JAVA
51
字号
package com.tarena.exam.dao;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import com.tarena.exam.model.Student;

public class StudentDaoFromTextFile implements StudentDao{
	private File file;
	
	public StudentDaoFromTextFile(File f){
		this.file=f;
	}
	
	public Student getStudent(int id, String passwd) {
		FileInputStream fis=null;
		BufferedReader br=null;
		try {
			fis=new FileInputStream(file);
			br=new BufferedReader(new InputStreamReader(fis));
			String str=null;
			while((str=br.readLine())!=null){
				String[] ss=str.split(":");
				if(Integer.parseInt(ss[0])==id && ss[2].equals(passwd)){
					return new Student(ss[1],id,ss[2]);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(br!=null)try{br.close();}catch(IOException e){}
			if(fis!=null)try{fis.close();}catch(IOException e){}
		}
		return null;
	}
	
//	public static void main(String[] args){
//		StudentDao dao=new StudentDaoFromTextFile(new File("student.dat"));
//		Student s=dao.getStudent(1005,"1234");
//		if(s!=null){
//			System.out.println(s.getName()+",欢迎登录!");
//		}else{
//			System.out.println("ID 或密码不正确!");
//		}
//	}
	
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?