read String from FileChannel - Java java.nio.channels

Java examples for java.nio.channels:FileChannel

Description

read String from FileChannel

Demo Code


//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    public static String readString(int finalname_offset, FileChannel fc)
            throws IOException {
        fc.position(finalname_offset);/*from  ww  w  .  jav a2s. co  m*/
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ByteBuffer buffer = ByteBuffer.allocate(1);
        while ((fc.read(buffer) > 0) && (buffer.get(0) != 0)) {
            bos.write(buffer.array());
            buffer.clear();
        }

        byte[] bys = bos.toByteArray();

        return new String(bys);
    }
}

Related Tutorials