1. Store the data in the collection into a text file case:
Requirement: To store string data in the ArrayList collection into a text file?
(1) Analysis:
Through the meaning of the topic, we can know some of the following things,
A string is stored in the ArrayList collection.
Traverse the ArrayList collection to get the data.
It is then stored in a text file.
The text file description uses a character stream .
(2)
Data Source :
Arraylist<string>--Traversal to get each string of data
Destination :
A.txt--FileWriter--BufferedWriter
2. code example:
1 Packagecn.itcast_02;2 3 ImportJava.io.BufferedWriter;4 ImportJava.io.FileWriter;5 Importjava.io.IOException;6 Importjava.util.ArrayList;7 8 /*9 * Ten * Data Source: One * arraylist<string>--traverse to get each string data A * Destination: - * A.txt --FileWriter--BufferedWriter - */ the Public classArraylisttofiledemo { - Public Static voidMain (string[] args)throwsIOException { - //encapsulating a data source (creating a Collection Object) -arraylist<string> array =NewArraylist<string>(); +Array.add ("Hello"); -Array.add ("World"); +Array.add ("Java"); A at //Package Destination -BufferedWriter BW =NewBufferedWriter (NewFileWriter ("A.txt")); - - //iterating through the collection - for(String s:array) { - //Write Data in Bw.write (s); - bw.newline (); to Bw.flush (); + } - the //Freeing Resources * bw.close (); $ }Panax Notoginseng}
Run the effect as follows:
Java Fundamentals Hardening IO flow notes 45:io stream exercises data stored in a collection into a text file case