程序10-8
import java.io.*;
public class PrintWriterTest {
public static void main(String args[]) {
try {
PrintWriter out = new PrintWriter(new FileWriter("myAccount2.dat"));
BankAccount aBankAccount = new BankAccount("LiuWei",3000);
out.println(aBankAccount.getOwnerName());
out.println(aBankAccount.getAccountNumber());
out.println("$" + aBankAccount.getBalance());
out.close();
} catch (FileNotFoundException e) {
System.out.println("Error,Cannot open file for writing.");
} catch (IOException e) {
System.out.println("Error,Cannot write to file.");
}
}
}
BankAccount类如下:
class BankAccount{
String ownerName;
int accountNumber;
float balance;
String getOwnerName()
{
return ownerName;
}
void setOwnerName (String ownerName)
{
this.ownerName = ownerName;
}
int getAccountNumber() {
return accountNumber;
}
void setAccountNumber (int accountNumber) {
this.accountNumber = accountNumber;
}
float getBalance() {
return balance;
}
void setBalance (float balance){
this.balance = balance;
}
BankAccount(String ownername,int accountnumber)
{
this.ownerName = ownername;
this.accountNumber = accountnumber;
}
BankAccount(String ownername,int accountnumber,float balance)
{
this.ownerName = ownername;
this.accountNumber = accountnumber;
this.balance = balance;
}
}