Java reading a file into an ArrayList?

后端 未结 13 986
醉话见心
醉话见心 2020-11-22 12:05

How do you read the contents of a file into an ArrayList in Java?

Here are the file contents:

cat
ho         


        
13条回答
  •  伪装坚强ぢ
    2020-11-22 12:54

    Here is an entire program example:

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class X {
        public static void main(String[] args) {
        File f = new File("D:/projects/eric/eclipseworkspace/testing2/usernames.txt");
            try{
                ArrayList lines = get_arraylist_from_file(f);
                for(int x = 0; x < lines.size(); x++){
                    System.out.println(lines.get(x));
                }
            }
            catch(Exception e){
                e.printStackTrace();
            }
            System.out.println("done");
    
        }
        public static ArrayList get_arraylist_from_file(File f) 
            throws FileNotFoundException {
            Scanner s;
            ArrayList list = new ArrayList();
            s = new Scanner(f);
            while (s.hasNext()) {
                list.add(s.next());
            }
            s.close();
            return list;
        }
    }
    

提交回复
热议问题