这可能有什么问题?

时间:2013-12-12 06:02:45

标签: java

有谁能告诉我这里可能出错的地方?

    import java.io.BufferedInputStream;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Arrays;
    import java.io.IOException;

    public class TopWordsFinder {

      /**
       * Map of <word length, <word content, count in text>> Use some different, or
       * even multiple data structures if it makes more sense to you.
       */
      Map<Integer, Map<String, Integer>> wordsByLength = new HashMap<>();

      public static void main(String[] args) {
        new TopWordsFinder().findTopWords();
      }

      private void findTopWords() {
        readWords(); // Read words to data structure
        printTopWords(); // Print words from data structure
      }

      // Reads words from file and stores in some data structure
      // Make sure to check the definition of word in context of this puzzle in
      // class javadoc
   private void readWords() {
        BufferedInputStream in = new BufferedInputStream(TopWordsFinder.class.getResourceAsStream("c:/book-text.txt"));
        StringBuilder word = new StringBuilder("");
        try{
            while (in.available() > 0) {
                char c = (char) in.read();
                if(Character.isAlphabetic(c)){
                    if(Character.isUpperCase(c)){
                        c = Character.toLowerCase(c);
                    }
                    word.append(c);
                }else{
                    saveWord(word.toString());
                    word.delete(0, word.length()-1);// Reset the sequence
                }
            }
        } catch (IOException e) {
            System.out.println("Error: "+e);
        }
    }
private void printTopWords() {
        Integer[] lengths = wordsByLength.keySet().toArray(new Integer[wordsByLength.keySet().size()]);
        Arrays.sort(lengths);
        for(int i = lengths.length-1; i>=0; i--){
            for(String word : wordsByLength.get(lengths[i]).keySet()){
                if(wordsByLength.get(lengths[i]).get(word) >= 3){
                    System.out.println("Sõna: "+word+" sõna pikkus: "+word.length()+" kordusi: "+wordsByLength.get(lengths[i]).get(word));
                    return;
                }
            }
        }
    }

 private void saveWord(String word) {
    // FILL IN HERE: Store word in data structure you chose
        if(wordsByLength.get(word.length()) == null){
            wordsByLength.put(word.length(), new HashMap<String, Integer>());
        }
        if(wordsByLength.get(word.length()) == null){
            wordsByLength.get(word.length()).put(word, 1);
        }else{
            int n = wordsByLength.get(word.length()).get(word);
            wordsByLength.get(word.length()).put(word, ++n);
        }
    }
}

这是我的java工作,但我得到Error: java.io.IOException: Stream closed

6 个答案:

答案 0 :(得分:1)

这是你的IO异常

}catch (IOException e) {
  System.out.println("Error: "+e);
 }

你的char c = (char) in.read();可以扔掉它 当流本身被破坏或在读取数据期间发生某些错误时,例如安全异常,权限被拒绝等和/或从IOEXception派生的一组异常。

为了更好地了解您应该在System.out.println("Error: " +e.getMessage())

中使用catch block

答案 1 :(得分:0)

对我来说,你似乎没有关闭流。我希望这可以在最后一个块中...我无法找到这个块。

BufferedInputStream in = new BufferedInputStream(TopWordsFinder.class.getResourceAsStream("c:/book-text.txt"));

这样的东西
finally
{
    in.close();
}

点击此处了解更多详情:http://www.javapractices.com/topic/TopicAction.do?Id=8

答案 2 :(得分:0)

我猜是问题出在in.avaialble()方法中。

来自doc

  

如果此输入流已关闭,则此方法中会发生IOException   通过调用close()方法,或发生I / O错误。

但您尚未关闭该流。所以我的猜测就是问题在于

BufferedInputStream in = new BufferedInputStream(TopWordsFinder.class.getResourceAsStream("c:/book-text.txt"));

检查您的文件路径是否正常或此行中是否有任何其他问题。

并在完成任务后(优先在finally块中)

关闭流

答案 3 :(得分:0)

我认为你可能想要使用扫描仪,你的代码会像这样更容易阅读

private void readWords() {
  FileInputStream in = new FileInputStream("c:/book-text.txt");
  Scanner scanner = new Scanner(in);
  try {
    while (scanner.hasNext()) {
      String word = scanner.next();
      if (word != null) {
        saveWord(word.toLowerCase());
      } else {
        break;
      }
    }
  } catch (IOException e) {
    System.out.println("Error: " + e.getMessage());
    e.printStackTrace();
  } finally {
    scanner.close();
  }
}

答案 4 :(得分:0)

你应该使用: -

FileInputStream fin = new FileInputStream("c:/book-text.txt");
BufferedInputStream in = new BufferedInputStream(fin);

答案 5 :(得分:0)

您从以下try-catch块获取错误消息

}catch (IOException e) {
  System.out.println("Error: "+e);
 }

原因:您没有检查文件是否已正确打开。 将代码打开到try-catch块中,如果文件没有正确打开:

private void readWords() {
        FileInputStream fis = null;
        BufferedInputStream in = null;

        try {
            fis = new FileInputStream(new File("c:/book-text.txt"));
            in = new BufferedInputStream(fis);
        } catch (Exception e1) {
            e1.printStackTrace();
            return; // unable to open file, so should not proceed further in
                    // readWords
        }

此外,您需要使用saveWord方法修复代码,因为此行空检查不正确:

if(wordsByLength.get(word.length()) == null){
}
if(wordsByLength.get(word.length()) == null){
} else {}

应该是:

private void saveWord(String word) {
    // FILL IN HERE: Store word in data structure you chose
    if (wordsByLength.get(word.length()) == null) {
        wordsByLength.put(word.length(), new HashMap<String, Integer>());
        wordsByLength.get(word.length()).put(word, 1);
    } else {
        int n = wordsByLength.get(word.length()).get(word);
        wordsByLength.get(word.length()).put(word, ++n);
    }
}