📄 filerw.java
字号:
package Bank;
import java.util.*;
import java.io.*;
/**
* 对保存帐户信息的数据文件进行读取操作
* 文件格式:同类数据在同一行保存,多个数据以分隔符分开
* @author rainliu
*/
public class FileRW extends ADataFile implements IDataFile {
/** 保存帐号信息的数据文件 */
private static String dataFileName = "src/banking/account.dat";
public FileRW() {
}
/**
* 从数据文件中读取帐户信息
* @return List 帐户信息的参数名和参数值
*/
public List readAccountInfo() {
//保存一组用户信息的列表
List accountList = new ArrayList();
//检查数据文件是否存在
if (checkFile(dataFileName)==false) return null;
try
{
java.io.FileReader r = new FileReader(dataFileName);
BufferedReader br = new BufferedReader(r);
//读取帐号ID
String accountId = br.readLine();
if (accountId==null) return null;
//password
String password = br.readLine();
if (password==null) return null;
//金额
String strBalance = br.readLine();
if (strBalance==null) return null;
//分出各个帐户的信息
StringTokenizer stId = new StringTokenizer(accountId,",");
StringTokenizer stPass = new StringTokenizer(password,",");
StringTokenizer stBalance = new StringTokenizer(strBalance,",");
while (stId.hasMoreTokens()) {
String tempID = stId.nextToken();
String tempPass = stPass.nextToken();
String tempBalance = stBalance.nextToken();
double tempB = Double.parseDouble(tempBalance);
AccountInfo ai = new AccountInfo(tempID,tempPass,tempB);
accountList.add(ai);
}
} catch (Exception e) {
e.printStackTrace();
}
return accountList;
}
/**
* 将帐户信息列表写入数据文件中
* @param List 要保存到文件中的帐户信息
* @return boolean 操作成功返回true,否则返回false
*/
public boolean writeAccountInfo(List accountList) {
boolean result = false;
//检查数据文件是否存在
if (!checkFile(dataFileName)) return false;
try
{
//将帐户信息写入文件中
java.io.FileWriter w = new FileWriter(dataFileName);
BufferedWriter bw = new BufferedWriter(w);
//所有帐户名字信息以“,”连接
String allId = "";
String allPass = "";
String allBalance = "";
for (int i=0;i<accountList.size();i++) {
AccountInfo tempAccount = (AccountInfo)accountList.get(i);
allId += tempAccount.accountId + ",";
allPass += tempAccount.password + ",";
allBalance += tempAccount.balance + ",";
}
String ls = System.getProperty("line.separator");
bw.write(allId+"\n");
bw.write(allPass+"\n");
bw.write(allBalance+"\n");
bw.flush();
bw.close();
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 检查文件是否存在,若不存在,则新建
* @return boolean 操作成功返回true,否则返回false
*/
public boolean checkFile(String fileName) {
boolean result = false;
try {
//如果该文件不存在,则在banking目录下创建一个新的文件
File file = new File(fileName);
if (!file.exists()) {
//若路径不存在,先创建路径
//File pathFile = dataFile.getParentFile();
File pathFile = new File(file.getParent());
if (!pathFile.exists()) {
pathFile.mkdirs();
}
//在指定路径下创建该文件
file.createNewFile();
}
result = true;
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -