10.5 ArrayList collection and stream io

1.ArrayListToFile

day10_io_fileWrite_Read.arraylist_tofile Package; 

Import java.io.BufferedWriter; 
Import java.io.FileWriter; 
Import java.io.IOException; 
Import of java.util.ArrayList; 

/ * 
 * the character string data storage ArrayList set to a text file 
 * Per a string element as a row in the data file 
 * 
 * analysis: 
 * a: Create a set of objects 
 * B: to add a collection string elements 
 * C: create an output stream object buffer 
 * D: through the collection, each string element to give and then writes the character string data element as a text file 
 * E: releasing resources 
 * / 
public  class ArrayListToFile {
     public  static  void main (string [] args) throws IOException { 
        the ArrayList <string> ArrayList = new new ArrayList<String> ();

        String[] arr = {"hello","java","world"};

        for(int i=0;i<arr.length;i++) {
            arraylist.add(arr[i]);
        }

//      //原始代码
//        for(int i=0;i<arraylist.size();i++) {
//            System.out.println(arraylist.get(i));
//        }

        BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));

        for(int i=0;i<arraylist.size();i++) {
            String s = arraylist.get(i);
            bw.write(s);
            bw.newLine();
            bw.flush();
        }

        bw.close();
    }
}

 

2.FileToArrayList

day10_io_fileWrite_Read.arraylist_tofile Package; 

Import java.io.BufferedReader; 
Import java.io.FileNotFoundException; 
Import java.io.FileReader; 
Import java.io.IOException; 
Import of java.util.ArrayList; 
/ * 
 * read data from a text file ArrayList to the collection, and through the collection 
 * each row of data as a string element 
 * 
 * analysis: 
 * a: Create Object stream input buffer 
 * B: creating a collection of objects 
 * C: read data, each row of data is read, the the line data element is stored as a set of 
 * D: releasing resources 
 * E: through the collection 
 * / 
public  class FileToArrayList {
     public  static  void main (String [] args) throws IOException { 
        the BufferedReader br =  new BufferedReader(new FileReader("c.txt"));
        ArrayList<String> arraylist = new ArrayList<String>();

        String len;
        while((len=br.readLine())!=null) {
            arraylist.add(len);
        }

        br.close();

        for(int i=0;i<arraylist.size();i++) {
            System.out.println(arraylist.get(i));
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/longesang/p/11083635.html