更高效还是更现代?使用Java读入和排序文本文件

Ste*_*eve 8 java sorting collections text file

我一直在尝试升级我的Java技能以使用更多的Java 5和Java 6.我一直在玩一些编程练习.我被要求从文本文件中读取段落并输出排序(降序)单词列表并输出每个单词的计数.

我的代码如下.

我的问题是:

  1. 我的文件输入例程是最尊重JVM资源的吗?

  2. 是否可以在读取文件内容和将内容放入可以生成单词排序列表的集合方面减少步骤?

  3. 我是否以最有效的方式使用Collection类和接口?

非常感谢任何意见.我只想尝试一些乐趣并提高我的编程技巧.

import java.io.*;
import  java.util.*;

public class Sort
{
    public static void main(String[] args)
    {
        String   sUnsorted       = null;
        String[] saSplit         = null;

        int iCurrentWordCount    = 1;
        String currentword       = null;
        String pastword          = "";

        // Read the text file into a string
        sUnsorted = readIn("input1.txt");

        // Parse the String by white space into String array of single words
        saSplit   = sUnsorted.split("\\s+");

        // Sort the String array in descending order
        java.util.Arrays.sort(saSplit, Collections.reverseOrder());


        // Count the occurences of each word in the String array
        for (int i = 0; i < saSplit.length; i++ )
        {

            currentword = saSplit[i];

            // If this word was seen before, increase the count & print the
            // word to stdout
            if ( currentword.equals(pastword) )
            {
                iCurrentWordCount ++;
                System.out.println(currentword);
            }
            // Output the count of the LAST word to stdout,
            // Reset our counter
            else if (!currentword.equals(pastword))
            {

                if ( !pastword.equals("") )
                {

                    System.out.println("Word Count for " + pastword + ": " + iCurrentWordCount);

                }


                System.out.println(currentword );
                iCurrentWordCount = 1;

            }

            pastword = currentword;  
        }// end for loop

       // Print out the count for the last word processed
       System.out.println("Word Count for " + currentword + ": " + iCurrentWordCount);



    }// end funciton main()


    // Read The Input File Into A String      
    public static String readIn(String infile)
    {
        String result = " ";

        try
        {
            FileInputStream file = new FileInputStream (infile);
            DataInputStream in   = new DataInputStream (file);
            byte[] b             = new byte[ in.available() ];

            in.readFully (b);
            in.close ();

            result = new String (b, 0, b.length, "US-ASCII");

        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }

        return result;
    }// end funciton readIn()

}// end class Sort()

/////////////////////////////////////////////////
//  Updated Copy 1, Based On The Useful Comments
//////////////////////////////////////////////////

import java.io.*;
import java.util.*;

public class Sort2
{
    public static void main(String[] args) throws Exception
    {
        // Scanner will tokenize on white space, like we need
        Scanner scanner               = new Scanner(new FileInputStream("input1.txt"));
        ArrayList <String> wordlist   = new  ArrayList<String>();
        String currentword            = null;   
        String pastword               = null;
        int iCurrentWordCount         = 1;       

        while (scanner.hasNext())
            wordlist.add(scanner.next() );

        // Sort in descending natural order
        Collections.sort(wordlist);
        Collections.reverse(wordlist);

        for ( String temp : wordlist )
        {
            currentword = temp;

            // If this word was seen before, increase the count & print the
            // word to stdout
            if ( currentword.equals(pastword) )
            {
                iCurrentWordCount ++;
                System.out.println(currentword);
            }
            // Output the count of the LAST word to stdout,
            // Reset our counter
            else //if (!currentword.equals(pastword))
            {
                if ( pastword != null )
                    System.out.println("Count for " + pastword + ": " +  
                                                            CurrentWordCount);   

                System.out.println(currentword );
                iCurrentWordCount = 1;    
            }

            pastword = currentword;  
        }// end for loop

        System.out.println("Count for " + currentword + ": " + iCurrentWordCount);

    }// end funciton main()


}// end class Sort2
Run Code Online (Sandbox Code Playgroud)

小智 4

  1. 在 Java 中,有更惯用的方式读取文件中的所有单词。 BreakIterator是从输入中读取单词的更好方法。

  2. 几乎在所有情况下都使用List<String>而不是。Array从技术上讲,数组不是 的一部分,并且不像,和那样Collection API容易替换实现。ListSetMap

  3. 你应该使用 aMap<String,AtomicInteger>来统计字数,而不是Array一遍又一遍地走。AtomicInteger是可变的,与此不同Integer,您可以只incrementAndGet()在一个恰好是线程安全的操作中进行操作。一个SortedMap实现也会给你按顺序排列的单词及其计数。

  4. final创建尽可能多的变量,甚至是局部变量。并在使用它们之前声明它们,而不是在顶部声明它们的预期范围会丢失。

  5. 在执行磁盘 IO 时,您几乎应该始终使用BufferedReader或 ,BufferedStream其适当的缓冲区大小等于磁盘块大小的倍数。

也就是说,在你有“正确”的行为之前,不要关心微观优化。