?? filerw.java
字號(hào):
package Bank;
import java.util.*;
import java.io.*;
/**
* 對(duì)保存帳戶信息的數(shù)據(jù)文件進(jìn)行讀取操作
* 文件格式:同類數(shù)據(jù)在同一行保存,多個(gè)數(shù)據(jù)以分隔符分開
* @author rainliu
*/
public class FileRW extends ADataFile implements IDataFile {
/** 保存帳號(hào)信息的數(shù)據(jù)文件 */
private static String dataFileName = "src/banking/account.dat";
public FileRW() {
}
/**
* 從數(shù)據(jù)文件中讀取帳戶信息
* @return List 帳戶信息的參數(shù)名和參數(shù)值
*/
public List readAccountInfo() {
//保存一組用戶信息的列表
List accountList = new ArrayList();
//檢查數(shù)據(jù)文件是否存在
if (checkFile(dataFileName)==false) return null;
try
{
java.io.FileReader r = new FileReader(dataFileName);
BufferedReader br = new BufferedReader(r);
//讀取帳號(hào)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;
//分出各個(gè)帳戶的信息
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;
}
/**
* 將帳戶信息列表寫入數(shù)據(jù)文件中
* @param List 要保存到文件中的帳戶信息
* @return boolean 操作成功返回true,否則返回false
*/
public boolean writeAccountInfo(List accountList) {
boolean result = false;
//檢查數(shù)據(jù)文件是否存在
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目錄下創(chuàng)建一個(gè)新的文件
File file = new File(fileName);
if (!file.exists()) {
//若路徑不存在,先創(chuàng)建路徑
//File pathFile = dataFile.getParentFile();
File pathFile = new File(file.getParent());
if (!pathFile.exists()) {
pathFile.mkdirs();
}
//在指定路徑下創(chuàng)建該文件
file.createNewFile();
}
result = true;
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -