返回顶部

收藏

java使用StreamTokenizer类

更多

下面代码演示如何使用StreamTokenizer类来数文本文件中有多少个单词,有多少个数字。

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;

/**
 *
 * @author outofmemory.cn
 */
public class Main {

    /**
     * StreamTokenizer 类使用示例
     */
    public void countWordsAndNumbers(String filename) {

        StreamTokenizer sTokenizer = null;
        int wordCount = 0, numberCount = 0;

        try {

            sTokenizer = new StreamTokenizer(new FileReader(filename));

            while (sTokenizer.nextToken() != StreamTokenizer.TT_EOF) {

                if (sTokenizer.ttype == StreamTokenizer.TT_WORD)
                    wordCount++;
                else if (sTokenizer.ttype == StreamTokenizer.TT_NUMBER)
                    numberCount++;
            }

            System.out.println("Number of words in file: " + wordCount);
            System.out.println("Number of numbers in file: " + numberCount);

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().countWordsAndNumbers("myFile.txt");
    }
}

文件内容为: 5 ants is more than 4 elephants

输出:

"Number of words in file: 5"
"Number of numbers in file: 2"

标签:java,IO

收藏

0人收藏

支持

0

反对

0

发表评论