Error whilst using StringTokenizer on text file with multiple lines

前端 未结 4 1205
我在风中等你
我在风中等你 2021-01-07 11:11

I\'m trying to read a text file and split the words individually using string tokenizer utility in java.

The text file looks like this;

a 2000

4  
b         


        
4条回答
  •  一整个雨季
    2021-01-07 11:41

    You need to use hasMoreTokens() method. Also addressed various coding standard issues in your code as pointed out by JB Nizet

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    
    public class TestStringTokenizer {
    
        /**
         * @param args
         * @throws IOException 
         */
        public static void main(String[] args) throws IOException {
            String fileSpecified = args[0];
    
            fileSpecified = fileSpecified.concat(".txt");
            String line;
            System.out.println ("file Specified = " + fileSpecified);
    
            ArrayList  words = new ArrayList ();
    
            BufferedReader br =  new BufferedReader (new FileReader (fileSpecified));
            try{
                while ((line  = br.readLine()) != null) {
                    StringTokenizer token = new StringTokenizer (line);
                    while(token.hasMoreTokens())
                        words.add(token.nextToken());
                }
            } catch (IOException e) {
                System.out.println (e.getMessage());
                e.printStackTrace();
            } finally {
                br.close();
            }
    
            for (int i = 0; i < words.size(); i++) {
                System.out.println ("words = " + words.get(i));
            }
        }
    }
    

提交回复
热议问题