字符串的大文本文件?

时间:2013-12-03 01:20:45

标签: java string frequency

好吧所以我知道这段代码并不完全正统,但不管它编译和放大运行。问题是,一旦我通过命令行输入txt文件,它只将文件中的第一行转换为String文本。 (是的,我知道我正在使用nextLine()方法。这是临时的,直到我找到更好的方法)。如何将整个txt文件(包含换行符)整合到一个字符串中?提前感谢任何建议/提示。

    import java.util.*;


    public class Concordance{

    static Scanner kb;


    public static void main(String arg[]){
        //input text file, create array, create List, and call other methods

        kb = new Scanner(System.in);

        String text = kb.nextLine();
        String[] words = text.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
        List<String> list = Arrays.asList(text.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+"));
        System.out.println("number of words in text (including duplicates) is: " + words.length);

        System.out.println("");
        alphaPrint(list);
        System.out.println("");
        uniqueWord(list);
    }//end main


    //prints text in alphabetical order and counts unique words 
    public static void alphaPrint(List<String> list){
        int count = 0;
        TreeSet<String> uniqueWord = new TreeSet<String>(list);
        System.out.println("text in alphabetical order: ");
        Collections.sort(list);
        for (String word : uniqueWord) {
            System.out.println(word);
            count++;
        }
        System.out.println("");
        System.out.println("unique word count is: " + count);
    }//end alphaprint


    //method will find and print frequency counts
    public static void uniqueWord(List<String> list){

        System.out.println("text with word frequencies: ");

        TreeSet<String> uniqueWord = new TreeSet<String>(list);
        for (String word : uniqueWord) {
            System.out.println(word + ": " + Collections.frequency(list, word));

        }
    }//end unique word

}//end class

2 个答案:

答案 0 :(得分:0)

也许是这样的

StringBuilder s = new StringBuilder();
while(kb.hasNextLine()){
  s.append(kb.nextLine())
}
text = s.toString();

或者也许在while循环中构建数组..使用kb.hasNext(pattern)

----编辑 您可以使用./java filename&lt;运行该应用程序。 TextFile.txt的

答案 1 :(得分:0)

代码必须使用循环遍历提供的文件。这是一个例子:

public class FileToString {

    public static void main(String[] args) {
        System.out.println("Please Enter a File:");

        Scanner scanner = new Scanner(System.in);
        String fileName = scanner.nextLine();


        Scanner fileScanner;
        try {

            File file = new File(fileName);
            fileScanner = new Scanner(file);

            String text = "";

            while (fileScanner.hasNext()) {
                text += fileScanner.nextLine();
            }
            System.out.println(text);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}