用Java读取输入文件

时间:2016-02-29 20:37:12

标签: java parsing input compiler-errors

此程序的目的是读取输入文件并解析它以查找单词。我使用了一个类和实例化对象来保存每个唯一的单词以及输入文件中找到的该单词的计数。例如,对于一个句子“Word”被找到一次,“are”被找到一次,“fun”被找到两次,...这个程序忽略数字数据(例如0,1,......)以及标点符号(比如。,;: - )

分配不允许使用固定大小的数组来保存单词字符串或计数。无论输入文件的大小如何,程序都应该工作。

我收到以下编译错误: '<>'操作员不允许源级别低于1.7 [line:9]

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

public class Test {

public static void main(String args[]) throws IOException {


    HashMap<String,Word> map = new HashMap<>();

    // The name of the file to open.
    String fileName = "song.txt";

    // This will reference one line at a time
    String line = null;

    try {
        // FileReader reads text files in the default encoding.
        FileReader fileReader =
                new FileReader(fileName);

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader =
                new BufferedReader(fileReader);

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

            String[] words = line.split(" ");

            for(String word : words){
                if(map.containsKey(word)){
                    Word w = map.get(word);
                    w.setCount(w.getCount()+1);
                }else {
                    Word w = new Word(word, 1);
                    map.put(word,w);
                }
            }
        }

        // Always close files.
        bufferedReader.close();
    }
    catch(FileNotFoundException ex) {
        System.out.println(
                "Unable to open file '" +
                        fileName + "'");
    }
    catch(IOException ex) {
        System.out.println(
                "Error reading file '"
                        + fileName + "'");
        // Or we could just do this:
        // ex.printStackTrace();
    }



    for(Map.Entry<String,Word> entry : map.entrySet()){
        System.out.println(entry.getValue().getWord());
        System.out.println("count:"+entry.getValue().getCount());
    }
 }

   static class Word{

    public Word(String word, int count) {
        this.word = word;
        this.count = count;
    }

    String word;
    int count;

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}

}

2 个答案:

答案 0 :(得分:2)

替换

HashMap<String,Word> map = new HashMap<>();

使用:

HashMap<String,Word> map = new HashMap<String,Word>();

答案 1 :(得分:2)

您需要使用版本1.7或更高版本的JDK进行编译,或更改行:

HashMap<String,Word> map = new HashMap<>();

HashMap<String,Word> map = new HashMap<String,Word>();