Mr. V
Mr. V

Reputation: 19

What could be wrong here?

Can anyone give me what could be wrong here?

    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);
        }
    }
}

This is my java work, but I'm getting Error: java.io.IOException: Stream closed.

Upvotes: 1

Views: 126

Answers (6)

Infinite Recursion
Infinite Recursion

Reputation: 6557

You get the error message from the following try-catch block

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

Reason: You did not check if the file was opened properly. Put the code to open the file into a try-catch block and if the file is not opened properly:

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
        }

Also, you need to fix the code in saveWord method because this line null check is not proper:

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

It should be:

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);
    }
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201409

I think you might want to use a Scanner instead, your code would be easier to read like this

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();
  }
}

Upvotes: 0

pratim_b
pratim_b

Reputation: 1190

Here is your IO exception

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

Your char c = (char) in.read(); can throw it when either the stream itself is corrupted or some error occurred during reading the data i.e. Security Exceptions, Permission Denied etc and/or a set of Exceptions which are derived from IOEXception.

To know it better you should use System.out.println("Error: " +e.getMessage()) in your catch block

Upvotes: 1

Madhura
Madhura

Reputation: 589

You should use:-

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

Upvotes: 0

stinepike
stinepike

Reputation: 54672

My guess is The problem is in in.avaialble() method.

from the doc

IOException occurs in this method if this input stream has been closed by invoking its close() method, or an I/O error occurs.

but you haven't close the stream. so my guess is the problem is in the line

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

check if your file path is ok or is there any other problem in this line.

and always close the stream after completing the task ( prefereable in finally block)

Upvotes: 0

FrankB
FrankB

Reputation: 31

Seems to me you are not closing the stream. I would expect this in a finally block... I'm not able to locate this block.

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

Something like

finally
{
    in.close();
}

Check out here for more details: http://www.javapractices.com/topic/TopicAction.do?Id=8

Upvotes: 0

Related Questions