ฉันกำลังสร้างแอปพลิเคชันธนาคารขั้นพื้นฐาน แม้ว่าการใช้ภาษาจาวาจะอยู่ในระดับกลางก็ตาม ที่นั่นฉันใช้ไฟล์อินพุตและเอาต์พุตจำนวนมาก ระหว่างทางมีคำถามบางอย่างผุดขึ้นในใจของฉันเกี่ยวกับ file-i/o
ใน java
1) จะเกิดอะไรขึ้นถ้าฉันสร้างไฟล์ข้อความที่แตกต่างกันสองไฟล์สำหรับการเขียนและการอ่านออบเจ็กต์? มันสร้างความแตกต่างหรือไม่?
2) แล้วการระบุพาธ (หรือการให้ชื่อไฟล์) จะเป็นอย่างไรหากฉันใช้ //
แทน \\
3) ฉันจำเป็นต้องสร้างวัตถุไฟล์ใหม่เช่นนี้: File file=new File("C://Users//Documents//NetBeansProjects//BankFile_assignment.txt");
ในกรณีเฉพาะของฉันหรือไม่
สุดท้ายแต่ไม่ท้ายสุดหากคุณอาจสงสัยเกี่ยวกับคลาส file-i/o ของฉัน:
public class ReaderWriter {
public void writeToFile(List<BankAccount> accounts) {
try {
File file = new File("C://Users//Documents//NetBeansProjects//BankFile_assignment.txt");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(accounts);//take the arrayList
oos.flush();
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<BankAccount> readFromFile() {
List<BankAccount> readData = null;
try {
File file = new File("C://Users//Documents//NetBeansProjects//BankFile_assignment.txt");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
readData = (List<BankAccount>) ois.readObject();
ois.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
return readData;
}
}