简体   繁体   中英

Android - Reading from a txt file and adding to an ArrayList

I'm working on Android studio and I'm trying to create a random name generator that retrieves a name from the text file "RandomNames.txt" when a button is clicked. What I get instead is "RandomNames.txt" as the name instead of what's actually in the file. Does anyone have a solution for this? Thanks in advance.

private void GenerateRandomName() {
     ArrayList<String> arr = new ArrayList<String>();
     Scanner scan = new Scanner("RandomNames.txt");
     while(scan.hasNextLine()) {
         String s = scan.nextLine();
         arr.add(s);


     }
     scan.close();
     Random rand  = new Random();




     username = arr.get(rand.nextInt(arr.size()));



 }

Scanner 's string constructor reads input from the given string. If you want to treat it as a file, you need to use one of the constructors that takes a File , Path or InputStream . Eg:

 Scanner scan = new Scanner(new File("RandomNames.txt"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM