sometimes, we encounter situations where we write data to a text file separately. Like what:
requirement : To store string data in the ArrayList collection into a text file
Analysis :
A string class is stored in the A:arraylist collection
B: the file to be stored is a text file, so with a character stream, in order to quickly, with buffer character stream a
Data source:
Arraylist<string>-----iterate through the collection to get the data
Destination:
C.txt------FileWriter------bufferedwriter
1 public Static voidMain (string[] Args)throwsIOException {2 //Encapsulating Data (creating collection Objects)3Arraylist<string> Arry =NewArrayList ();4 //Add Data5Arry.add ("i");6Arry.add ("want");7Arry.add ("sleep. ");8 9 //Package DestinationTenBufferedWriter BW =NewBufferedWriter (NewFileWriter ("c.txt")); oneString line =NULL; a intLen = 0; - //iterate through the array, write the data to the destination - for(String S:arry) { the Bw.write (s); - Bw.newline (); - Bw.flush (); - } + bw.close (); - +}
again, Sometimes we need to extract the data from the text file and store it in the collection:
requirement: reads data from a text file (each behavior is a string of Data) into the collection and iterates through the collection
Analysis:
A: the data is read from a text file, the stream is entered with a buffered character Bufferreader
B: because in order to be fast, the use of each behavior is a string of data read, so the collection type is the String class
Data source:
Copy.txt--filereader--bufferedreader
Destination:
Arraylist<string>
1 public Static voidMain (string[] Args)throwsIOException {2 //Encapsulating Data Sources3BufferedReader br =NewBufferedReader (NewFileReader ("copy.txt"));4 //encapsulate Destination (create Collection)5Arraylist<string> Arry =NewArrayList ();6 //reads data from the data source and writes the data to the collection7String line =NULL;8 while(line = Br.readline ())! =NULL){9 Arry.add (line);Ten } one br.close (); a - //iterating through an array - for(String S:arry) { the System.out.println (s); - } - -}
Java 21-10 text files and collections store data between each other