流闭合错误Java

时间:2015-11-29 17:33:48

标签: java file-io inputstream huffman-code

我收到了Stream Closed Error。我正在尝试将一个霍夫曼树写入文本文件,但每次运行它时,都会弹出错误,说明该流已关闭。有什么想法吗?

    HuffmanTree Tree = new HuffmanTree();
    HuffmanTree.HuffData[] freqTable = null;
    BufferedReader in = null;
    ObjectOutputStream out = null;
    try{
    in = new BufferedReader(new FileReader("oddysy.txt"));

    freqTable = HuffmanTree.buildFreqTable(in);
    Tree.buildTree(freqTable);
    Tree.buildCodeTable();
    Tree.printCode(new PrintStream(new FileOutputStream("freqTable.txt")));

    Tree.encode(in, new ObjectOutputStream(new FileOutputStream("watsonStructure.txt")));
    } finally {
        if (in != null){
            in.close();
        }
        if (out != null){
            out.close();
        }
    }
}
java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(BufferedReader.java:122)
at java.io.BufferedReader.read(BufferedReader.java:179)
at HuffmanTree.encode(HuffmanTree.java:244)
at Huffman_Driver.main(Huffman_Driver.java:28)

1 个答案:

答案 0 :(得分:0)

这里的问题是你正在使用已经完成阅读的阅读器。

在下面的代码中,HuffmanTree使用缓冲的阅读器构建频率表。

in = new BufferedReader(new FileReader("oddysy.txt"));
freqTable = HuffmanTree.buildFreqTable(in);

现在BufferedReader读取文件中的所有数据并关闭流,因为没有数据可供读取。

您再次尝试使用相同的BufferedReader,读者从文件中读取所有数据并关闭流。因此,你得到了这个例外。

Tree.encode(in, new ObjectOutputStream(new FileOutputStream("watsonStructure.txt")));

如果您需要从同一个文件中读取数据,则必须再次初始化BufferedReader。