Java:Javolution:如何正确使用UTF8StreamReader?发生错误引起:java.lang.ArrayIndexOutOfBoundsException:2048

时间:2011-06-20 00:54:50

标签: java byte javolution

以下是代码:

public static void mergeAllFilesJavolution()throws FileNotFoundException, IOException {
    String fileDir = "C:\\TestData\\w12";
    File dirSrc = new File(fileDir);
    File[] list = dirSrc.listFiles();
    long start = System.currentTimeMillis();
    for(int j=0; j<list.length; j++){
        int chr;
        String srcFile = list[j].getPath();
        String outFile = fileDir + "\\..\\merged.txt";
        UTF8StreamReader inFile=new UTF8StreamReader().setInput(new FileInputStream(srcFile));
        UTF8StreamWriter outPut=new UTF8StreamWriter().setOutput(new FileOutputStream(outFile, true)); 
        while((chr=inFile.read()) != -1) {
            outPut.write(chr);
        }
        outPut.close();
        inFile.close();
    }
    System.out.println(System.currentTimeMillis()-start);
}

utf-8文件的文件大小为200MB作为测试数据,但高可能性为800MB

这是UTF8StreamReader.read()源代码。

/**
 * Holds the bytes buffer.
 */
private final byte[] _bytes;

/**
 * Creates a UTF-8 reader having a byte buffer of moderate capacity (2048).
 */
public UTF8StreamReader() {
    _bytes = new byte[2048];
}

/**
 * Reads a single character.  This method will block until a character is
 * available, an I/O error occurs or the end of the stream is reached.
 *
 * @return the 31-bits Unicode of the character read, or -1 if the end of
 *         the stream has been reached.
 * @throws IOException if an I/O error occurs.
 */
public int read() throws IOException {
    byte b = _bytes[_start];
    return ((b >= 0) && (_start++ < _end)) ? b : read2();
}

错误发生在_bytes [_start] ,因为_bytes = new byte [2048]。

这是另一个UTF8StreamReader构造函数:

/**
 * Creates a UTF-8 reader having a byte buffer of specified capacity.
 * 
 * @param capacity the capacity of the byte buffer.
 */
public UTF8StreamReader(int capacity) {
    _bytes = new byte[capacity];
}

问题:如何在创建UTF8StreamReader时指定_bytes 的正确容量?

尝试了File.length()但是它返回了long类型(我认为它正确,因为我期望文件大小很大,但构造函数只接受int类型)。

对正确方向的任何指导表示赞赏。

1 个答案:

答案 0 :(得分:0)

似乎任何人都没有遇到与上述情况相同的情况。

无论如何,我通过不使用上面的类(UTF8StreamReader)而不是ByteBuffer(UTF8ByteBufferReader)尝试了其他解决方案。它比StreamReader更快。

Faster Merging Files by using ByteBuffer