Mun*_*ira 0 java file-io arraylist fileinputstream fileoutputstream
我的目标是从文件中读取和写入对象(使用文件I/O).这些对象是存储在动态中的userinput(name,int value,double value等..)arrayList.将arrayList在我的主类中声明.作为我程序的进一步改进,我想将这些数据保存在一个文件中,我已经创建了另一个类ReaderWriter来实现file I/O.
现在,我怎么能得到的参考arrayList在ReaderWriter上课吗?
我的申请很大.我将展示与我的问题相关的部分内容:
主要:
public static void main(String[] args) {
System.out.println("WELCOME TO OUR BANK!\n\n");
List<BankAccount> bankAccounts = new ArrayList<BankAccount>();
}
Run Code Online (Sandbox Code Playgroud)
getter和setter的类:
public class BankAccount {
private String name;
private int accNum;
private double initiateAmount;
//constructor
public BankAccount() {
this.name = null;
this.accNum = 0;
this.initiateAmount = 0;
}
public void setName(String name) {
this.name = name;
.........................
.......................
............
Run Code Online (Sandbox Code Playgroud)
读写器:
public void writeToFile(){
try {
FileOutputStream fos=new FileOutputStream("C:\\Users\\Jabir Al Fatah\\Documents\\NetBeansProjects\\BankFile.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject();//take the arrayList variable
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void readFromFile(){
try {
FileInputStream fis=new FileInputStream("C:\\Users\\Jabir Al Fatah\\Documents\\NetBeansProjects\\BankFile.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
//make an arrayList to get those object back
//arrayList
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
您为writeToFile方法提供了一个具有ArrayList类型的参数.现在,您在main中创建一个ReaderWriter实例,并使用方法writeToFile.在readFromFile中,您必须添加一个返回语句,该语句也来自ArrayList类型.现在您可以使用methode填充ArrayList实例.
正确的代码:
public void writeToFile(ArrayList<BankAccount> accounts){
try {
FileOutputStream fos=new FileOutputStream("C:\\Users\\Jabir Al Fatah\\Documents\\NetBeansProjects\\BankFile.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(accounts);
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<BankAccount>readFromFile(){
try {
FileInputStream fis=new FileInputStream("C:\\Users\\Jabir Al Fatah\\Documents\\NetBeansProjects\\BankFile.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
//make an arrayList to get those object back and return the list
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
主要:
public static void main(String[] args) {
System.out.println("WELCOME TO OUR BANK!\n\n");
List<BankAccount> bankAccounts = new ArrayList<BankAccount>();
ReaderWriter rw = new ReaderWriter();
rw.writeToFile(bankAccounts);
List<BankAccount> bankAccounts2 = new ArrayList<BankAccount>();
bankAccounts2 = rw.readFromFile();
}
Run Code Online (Sandbox Code Playgroud)