Java IO类 - 文件IO的麻烦

时间:2012-04-29 14:08:22

标签: java input

我对BufferedReader进行了初始化:

Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"));

其中filename是任何给定的字符串。

当我通过循环处理输出时:

int k;
while((k = reader.read()) != -1){
        String entry;
        if (dict.containsKey(k))
            entry = dict.get(k);
        else if (k == mapSize)
            entry = w + w.charAt(0);
        else
            throw new IllegalArgumentException("Bad compressed k: " + k);
        this.fos.write(entry);
        result += entry;

        // Add w+entry[0] to the dictionary.
        dict.put(mapSize++, w + entry.charAt(0));

        w = entry;
}

在点击EOF之前它只读取65536个字符数。有谁知道这里发生了什么?

2 个答案:

答案 0 :(得分:2)

您无需致电ready()。只需阅读数据或行

String line;
while((line = reader.readLine()) != null) {
    //process, LZW algorithm
}

// buffer is redundant if you are reading large blocks.
Reader reader = new InputStreamReader(new FileInputStream(filename), "UTF-8");
char[] buffer = new char[8*1024];
int len;
while((len = reader.read(buffer)) > 0) {
    // process text
}

答案 1 :(得分:0)

您正在尝试将二进制数据作为字符数据读取。那会很糟糕。 utf8是一个多字节字符编码,这意味着从文件中读取的字符数可能不等于文件中的字节数。如果您正在尝试实施解压缩算法,则应该使用InputStream并读取 bytes ,而不是 chars