Java: Javolution: How to use UTF8ByteBufferWriter and MappedByteBuffer?

我怕爱的太早我们不能终老 提交于 2019-12-08 07:26:22

问题


To Anybody that uses the javolution, please guide me on how to use it. Any snippet code helps me a lot.

here's my current code:

public static void mergeAllFilesJavolution2()throws FileNotFoundException, IOException {
    String fileDir = "C:\\TestData\\w12";
    File dirSrc = new File(fileDir);
    File[] list = dirSrc.listFiles();
    long start = System.currentTimeMillis();

    String outFile = fileDir + "\\..\\merged.txt";
    File file2 = new File(outFile);
    //file2.createNewFile();
    FileChannel fc2 = (new RandomAccessFile(file2, "rw")).getChannel(); 

    for(int j=0; j<list.length; j++){
        int chr;
        String srcFile = list[j].getPath();

        File file = new File(srcFile);
        FileChannel fc = (new FileInputStream(file)).getChannel(); 
        MappedByteBuffer buf = fc.map(MapMode.READ_ONLY, 0, file.length());
        UTF8ByteBufferReader inFile= new UTF8ByteBufferReader().setInput(buf);

        MappedByteBuffer buf2 = fc2.map(MapMode.READ_WRITE, file2.length(), file.length());
        UTF8ByteBufferWriter outPut= new UTF8ByteBufferWriter().setOutput(buf2);

        while((chr=inFile.read()) != -1) {
            outPut.write(chr);
        }
        outPut.close();
        inFile.close();
    }
    System.out.println(System.currentTimeMillis()-start);
}

but it gives me an exception:

Exception in thread "main" java.nio.channels.NonReadableChannelException at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:716) at abc.filedivision.FileMergeTest.mergeAllFilesJavolution2(FileMergeTest.java:100) at abc.filedivision.FileMergeTest.main(FileMergeTest.java:27)

Any guidance on the right direction is appreciated.


回答1:


My guess is it is complaining here (thats why its important to look at the line of code which has the error)

FileChannel fc2 = (new FileOutputStream(file2, true)).getChannel(); 
MappedByteBuffer buf2 = fc2.map(MapMode.READ_WRITE, 0, file2.length());

This exception is thrown if you are trying to use the channel to read but it is not readable.

You can only open a channel in READ_WRITE mode if you use RandomAccessFile in "rw", "rws", or "rwd" modes



来源:https://stackoverflow.com/questions/6384641/java-javolution-how-to-use-utf8bytebufferwriter-and-mappedbytebuffer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!