简体   繁体   中英

Reading a file into Java using StringTokenizer

I'm trying to do a very simple task but I'm not getting the results I want. I have a text file with names separated by a comma on multiples lines and I want to store that information in a 1D array. When I run my code and try to print the array to make sure my information was recorded the console only prints out the last line of the text file. What is wrong with my code? I've tried playing around with it but I've found no solution to my problem. Is the information being overwritten?

import java.util.*;

public class Tokens {
public static TextFileInput myFile;
public static StringTokenizer myTokens;
public static String name;
public static String[] names;
public static String line;

public static void main(String[] args) {

myFile = new TextFileInput("namesofstudents.txt");

  while ((line = myFile.readLine())!= null) {       
     int i=0;    

     myTokens = new StringTokenizer(line, ",");
     names = new String[myTokens.countTokens()];

        while (myTokens.hasMoreTokens()){
          names[i] = myTokens.nextToken();
          i++;
     }        
  }    

for (int j=0;j<names.length;j++){
   System.out.println(names[j]);       
}


   } 
}

example of an input:

  Mark, Joe, Bob
  James, Jacob, Andy, Carl

output:

James
Jacob
Andy
Carl

The code initializes i to 0 at the beginning of every line. Do that at the beginning of the run.

Consider using an ArrayList which makes life easier...

List<String> names = new ArrayList<>();

while ((line = myFile.readLine())!= null) {           

 myTokens = new StringTokenizer(line, ",");     

    while (myTokens.hasMoreTokens()){
      names.add(myTokens.nextToken());
    }        
}    

System.out.println(names);       

You're restarting your count and rewriting names on each line.

Try creating names as an ArrayList .

ArrayList<String> names;

Initialize it once outside the first loop like this:

names = new ArrayList<String>();

Then each time you would normally put the name in the array replace this line:

names[i] = myTokens.nextToken();

With:

names.add(myTokens.nextToken());

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