1. Storing data in a text file in a collection
Requirement: Reads data from a text file (each behavior is a string of data) into the collection and iterates through the collection.
Analysis:
Through the meaning of the topic, we can know some of the following things,
The data source is a text file.
The destination is a collection.
And the element is a string.
Data Source :
B.txt--FileReader--BufferedReader
Destination :
Arraylist<string>
2. code example:
1 Packagecn.itcast_02;2 3 ImportJava.io.BufferedReader;4 ImportJava.io.FileReader;5 Importjava.io.IOException;6 Importjava.util.ArrayList;7 8 /*9 * Requirements: Read data from a text file (each behavior is a string of data) into the collection and iterate through the collectionTen * One * Analysis: A * Through the meaning of the topic, we can know the following content, - * The data source is a text file. - * Destination is a collection. the * and the element is a string. - * - * Data Source: - * B.txt --filereader--BufferedReader + * Destination: - * arraylist<string> + */ A Public classFiletoarraylistdemo { at Public Static voidMain (string[] args)throwsIOException { - //Encapsulating Data Sources -BufferedReader br =NewBufferedReader (NewFileReader ("B.txt")); - // Encapsulate Destination (Create collection Object) -arraylist<string> array =NewArraylist<string>(); - in //read data stored in the collection -String line =NULL; to while(line = Br.readline ())! =NULL) { + Array.add (line); - } the * //Freeing Resources $ br.close ();Panax Notoginseng - //iterating through the collection the for(String s:array) { + System.out.println (s); A } the } +}
Run the effect as follows:
Java Fundamentals Hardening IO flow notes 45:io Stream exercises the case of storing data in a text file in a collection