java数据库文件_[Java] 简单文件数据库实现

这篇博客介绍了如何使用Java实现一个简单的文件数据库,包括学生记录的增删改查操作。通过字符流操作文本文件,实现数据的管理。核心类DatabaseHelper包含了文件操作的主要逻辑,如向文件末尾追加数据、查找并删除指定数据等。博客提供了部分关键代码,并提到实际操作中数据删除的实现策略。
摘要由CSDN通过智能技术生成

昨晚上在设计项目数据库遇到点困难,刚好看到Java选修课群里说有个“大作业”。大概的意思就是一张固定的表,使用文件的方式管理这张表的数据,使其可以对数据进行"更删改查"。这不就是一个"数据库"么,当然和实际使用的数据库差很远,不过大体思想差不多是吧→_→(原谅我这个标题党)

题目描述:

利用字符流操作文本文件,实现 学生记录的增加、删除和更新;

记录的格式(学号,姓名,出生年月,专业) 数据项按“,”分割,一条记录为一行

之前可以说没有用过Java的文件操作,只看过Oracle 文档上关于I/O 流的介绍,借此机会练练手。

首先类的设计

StudentBean: 用户表示学生信息,亦即“数据库”中的表

DatabaseHelper: 数据库的工具类 实现更删改查(不过我这里将文件操作都扔里边了 耦合性高了点 懒的分出来了)

Menu: 菜单类 也就是用户操作界面了

Client: 主类 测试用

这里边最主要的就是 DatabaseHelper 的编写,属于这里边的核心类。

它包含学生记录的 增删改查

增: 向文件末尾写入一条数据

删: 首先查找数据位置,将文件中数据读取出来,删除再写入文件

改: 首先查找数据位置,再删除,修改后再写入

这几步当中,"删"较为复杂一点。开始的时候我是打算直接打开两个文件,一边读一遍写。这样同时操作就不需要

一次性将文件中的所有数据加载到内存了,相对来说对系统内存要求小一些,防止文件过大内存被用光。但是在实际的实现当中,数据产生混乱。数据的删除出现问题,最后还是采用将数据读出来再写进去的方法。这个方法很简单,就不做细节介绍了。删除记录完成了,更改数据就可以在"增"和“删”的基础上进行了。同时数据记录的查找就是上边操作的基础,就是做一个字符串匹配。

下边就贴两段代码,注释都很详细了。

这个程序关注的是核心功能的实现,对数据格式的没做太多限制,异常处理也不是很全面。不过正常的输入测试是没有问题的。代码耦合也没做太多考虑,讲究这看吧。文末会附上完整源码地址。(IntelliJ IDEA 工程)

StudentBean:

package com.mummyding.javacourse;

import java.util.Scanner;

/**

* Created by mummyding on 15-11-25.

*/

public class StudentBean {

private String studentID;

private String studentName;

private String birthDay;

private String major;

public String getStudentID() {

return studentID;

}

public boolean setStudentID(String studentID) {

this.studentID = studentID;

return true;

}

public String getStudentName() {

return studentName;

}

public void setStudentName(String studentName) {

this.studentName = studentName;

}

public String getBirthDay() {

return birthDay;

}

public void setBirthDay(String birthDay) {

this.birthDay = birthDay;

}

public String getMajor() {

return major;

}

public void setMajor(String major) {

this.major = major;

}

public boolean isDataComplete(){

if(studentID == null || studentName == null || birthDay == null || major == null){

return false;

}

return true;

}

public void readData(){

Scanner sc = new Scanner(System.in);

System.out.println("Input Student Info ,please! ");

System.out.println("Student ID: ");

setStudentID(sc.nextLine().trim());

System.out.println("Student Name: ");

setStudentName(sc.nextLine());

System.out.println("Student BirthDay: ");

setBirthDay(sc.nextLine());

System.out.println("Student Major: ");

setMajor(sc.nextLine());

}

@Override

public String toString() {

return getStudentID()+","+getStudentName()+","+getBirthDay()+","+getMajor();

}

}

DataBaseHelper

package com.mummyding.javacourse;

import java.io.*;

import java.util.ArrayList;

import java.util.List;

/**

* Created by mummyding on 15-11-25.

*/

public class DatabaseHelper {

public static boolean isFileCreateSuccessful = true;

public static final String fileName = "FileDatabase.txt";

private static File file;

private static BufferedWriter writer;

private static FileWriter fileWriter;

private static BufferedReader reader;

private static FileReader fileReader;

/*

initialize basic data in static scope.

create database file (singleton)

*/

static {

file = new File(fileName);

/*

check file is exist or not,create if it not exist.

set isFileCreateSuccessful to false if create fail.

*/

if(file.exists() == false){

try {

file.createNewFile();

} catch (IOException e) {

e.printStackTrace();

isFileCreateSuccessful = false;

System.out.println("Database initialize fail");

}

}

}

/*

the following is basic operating of database methods.

addData updateData and deleteData.

*/

/*

insert a record to file database.

*/

public static boolean addData(StudentBean data){

if(dataCheck(data) == false) return false;

try {

initWriter();

writer.write(data.toString());

writer.newLine();

writer.flush();

} catch (IOException e) {

e.printStackTrace();

return false;

}finally {

try {

writer.close();

fileWriter.close();

}catch (IOException e) {

e.printStackTrace();

return false;

}

}

return true;

}

/*

update a record by student id.

*/

public static boolean updateData(String studentID,StudentBean data){

if(dataCheck(data) == false) return false;

if(deleteData(studentID)){

addData(data);

return true;

}

return false;

}

/*

delete a record by student id.

*/

public static boolean deleteData(String studentID){

int lineNumber = findDataByStudent(studentID);

if(lineNumber != -1){

deleteDataByLineNumber(lineNumber);

return true;

}

return false;

}

/*

the following is basic utils of class

initWriter initReader findDataByStudent and deleteDataByLineNumber

*/

private static boolean dataCheck(StudentBean data){

if(isFileCreateSuccessful == false){

System.out.println("Database doesn't exist, insert fail");

return false;

}

if(data.isDataComplete() == false){

System.out.println("Record is not complete, insert fail");

return false;

}

return true;

}

/*

initialize BufferedWriter FileWriter.

*/

private static boolean initWriter(){

/*

create FileWriter and BufferWriter.

*/

try {

writer = new BufferedWriter(fileWriter =new FileWriter(file,true));

return true;

} catch (IOException e) {

e.printStackTrace();

return false;

}

}

/*

initialize BufferedReader FileReader.

*/

private static boolean initReader(){

/*

create FileReader and BufferReader.

*/

try {

reader = new BufferedReader(fileReader = new FileReader(file));

return true;

} catch (IOException e) {

e.printStackTrace();

return false;

}

}

/*

find record linenumber in file database by student id.

*/

private static int findDataByStudent(String studentID){

initReader();

String tmpStr;

boolean isFind =false;

int lineNumber = -1;

int currentLineNumber =0;

try {

initReader();

while ((tmpStr = reader.readLine()) != null && isFind == false){

int pos = tmpStr.indexOf(studentID);

if(pos>=0&&tmpStr.charAt(studentID.length())==','&&tmpStr.substring(0,studentID.length()).equals(studentID)){

lineNumber = currentLineNumber;

isFind = true;

}

currentLineNumber++;

}

} catch (IOException e) {

e.printStackTrace();

}finally {

try {

reader.close();

fileReader.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return lineNumber;

}

/*

delete a record from file database by linenumber.

*/

private static boolean deleteDataByLineNumber(int lineNumber){

List lines = new ArrayList<>();

RandomAccessFile oldFile = null,newFile = null;

try {

oldFile = new RandomAccessFile(file,"r");

newFile = new RandomAccessFile(file,"rw");

oldFile.seek(0);

String tmpStr;

while((tmpStr = oldFile.readLine()) != null){

lines.add(tmpStr);

}

new FileOutputStream(file, false);

newFile.seek(0);

lines.remove(lineNumber);

for(int i =0 ; i

newFile.writeBytes(lines.get(i));

newFile.writeBytes("\n");

}

} catch (FileNotFoundException e) {

e.printStackTrace();

return false;

} catch (IOException e) {

e.printStackTrace();

return false;

}finally {

try {

oldFile.close();

newFile.close();

} catch (IOException e) {

e.printStackTrace();

return false;

}

}

return true;

}

public static void printAllData(){

int currentLineNumber =-1;

try {

initReader();

String tmpStr;

while ((tmpStr = reader.readLine()) != null){

System.out.println(tmpStr);

currentLineNumber++;

}

} catch (IOException e) {

e.printStackTrace();

}finally {

try {

reader.close();

fileReader.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if(currentLineNumber == -1){

System.out.println("Database has no data");

}

}

}

【转载请注明出处】

Author: MummyDing

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值