Java Reference
In-Depth Information
if
( f i leChooser . showDialog (NotepadFrame .
this
,
"Save"
)==
JFileChooser .APPROVEOPTION)
{
File newFile = fileChooser . getSelectedFile() ;
try
(PrintWriter fileWritter =
new
PrintWriter(newFile))
{
fileWritter .print(textArea.getText());
}
catch
(Exception exception)
{
}
}
}
}
);
}
}
13.3 Data Files
We will next give an example of how to read and write binary data to and from a file.
We will create a simple bank application. The application will be by no means complete.
Rather, it will be a toy example that shows how objects can be read and written to a file.
The main
BankApp
class is shown next. It creates two customers and an employee and tests
how deposits and withdraws can be made and how binary data can be written to and from
afile.Notethatthe
main
method throws an exception. This is the reason we do not need
a
try-catch
block inside the method.
import
java . io .
;
import
java . util .
∗
;
∗
public class
BankApp
{
public static void
main(String [] args)
throws
Exception
{
ArrayList
<
Person
>
people =
new
ArrayList
<>
() ;
Customer bob =
new
Customer(
"Bob"
,
new
Person .Address(123 ,
"Main"
,
"Chicago"
,
"IL"
, 60641) , 5555555555L) ;
Customer ann =
new
Customer(
"Ann"
,
new
Person .Address(444 ,
"King"
,
"New York"
,
"NY"
, 10466) , 666666666L) ;
Employee suzan =
new
Employee(
"Susan"
,
new
Person .Address(444 ,
"
King"
,
"New York"
,
"NY"
, 10466) , 777777777L, 80000) ;
people .add(bob) ;
people . add(ann) ;
people .add(suzan) ;
BankAccount account1 =
new
BankAccount(1000, bob) ;
bob . addBankAccount( account1 ) ;
account1 . deposit(100000, suzan) ;
BankAccount account2 =
new
BankAccount(50000, ann) ;
ann . addBankAccount( account2 ) ;
account2 .withdraw(200 , suzan) ;
FileOutputStream fileOut =
new
FileOutputStream(
"bank.ser"
);
ObjectOutputStream out =
new
ObjectOutputStream( fileOut ) ;
out .writeObject(people) ;
out . close () ;
fileOut . close () ;
people =
null
;