Example usage for java.nio.channels FileChannel position

List of usage examples for java.nio.channels FileChannel position

Introduction

In this page you can find the example usage for java.nio.channels FileChannel position.

Prototype

public abstract FileChannel position(long newPosition) throws IOException;

Source Link

Document

Sets this channel's file position.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    FileChannel fc = new RandomAccessFile("data.txt", "rw").getChannel();
    fc.position(fc.size());
    fc.write(ByteBuffer.wrap("Some more".getBytes()));
    fc.close();//from w w w .  jav  a  2 s.  c o  m

}

From source file:GetChannel.java

public static void main(String[] args) throws Exception {
    // Write a file:
    FileChannel fc = new FileOutputStream("data.txt").getChannel();
    fc.write(ByteBuffer.wrap("Some text ".getBytes()));
    fc.close();/*from ww w . jav a 2 s  .  com*/
    // Add to the end of the file:
    fc = new RandomAccessFile("data.txt", "rw").getChannel();
    fc.position(fc.size()); // Move to the end
    fc.write(ByteBuffer.wrap("Some more".getBytes()));
    fc.close();
    // Read the file:
    fc = new FileInputStream("data.txt").getChannel();
    ByteBuffer buff = ByteBuffer.allocate(BSIZE);
    fc.read(buff);
    buff.flip();
    while (buff.hasRemaining())
        System.out.print((char) buff.get());
}

From source file:Main.java

/**
 * This method handels the write operations for a specified file.
 * //from  ww  w. j  a va 2  s . co m
 * @param file the file to which the data should be written.
 * @param data the data,which should be written to a specified file.
 * @param writeCompleted a flag which indicates, if writing to a file is complete, or
 *            if there data left, which should be append to the end of the
 *            file.
 */
public static void writeFile(File file, byte[] data, boolean writeCompleted) {
    // Writing the encrypted data with header
    try {

        if (fos == null)
            fos = new FileOutputStream(file);

        FileChannel fileChannel = fos.getChannel();

        if (writeStreamPosition != 0L)
            fileChannel.position(writeStreamPosition);

        fos.write(data);
        fos.flush();

        writeStreamPosition = fileChannel.position();

        // reset flags, if file-operation is completed
        if (writeCompleted) {
            fileChannel.close();
            fos.close();
            fos = null;
            writeStreamPosition = 0L;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}

From source file:Main.java

/**
 * This method handels the reading of data from a specific file.
 * //from  ww w  .  j av a2s . co m
 * @param file the file, to read from.
 * @param blockSize the length of the data-block, which should be read from the specified file.
 * @return the data read from the file.
 */
public static byte[] readFile(File file, long blockSize) {
    FileInputStream fis;
    byte[] fileContent = null;

    try {
        fis = new FileInputStream(file);

        FileChannel fileChannel = fis.getChannel();

        int bytesToRead;
        fileChannel.position(readStreamPosition);

        int dataLen = fis.available();

        // if there is a zero block size specified, read the whole file
        if (blockSize == 0L) {
            bytesToRead = dataLen;
        } else {
            bytesToRead = (int) blockSize;
        }

        fileContent = new byte[bytesToRead];

        // reading the data
        for (int i = 0; i < bytesToRead; i++) {
            fileContent[i] = (byte) fis.read();
        }

        // storing read-position
        readStreamPosition = fileChannel.position();

        fis.close();
        fileChannel.close();

        // zero blockSize indicates, that reading of this file is completed,
        // stream position reset
        if (blockSize == 0L) {
            readStreamPosition = 0L;
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return fileContent;
}

From source file:com.github.neoio.nio.util.NIOUtils.java

public static void resetFileChannel(FileChannel channel) throws NetIOException {
    try {/*  ww w  .  jav a2  s.c om*/
        channel.position(0);
        channel.truncate(0);
    } catch (IOException e) {
        throw new NetIOException(e);
    }
}

From source file:com.github.neoio.nio.util.NIOUtils.java

public static void resetFileChannelForReading(FileChannel channel) throws NetIOException {
    try {//from   w ww .jav a2  s  . co  m
        channel.force(true);
        channel.position(0);
    } catch (IOException e) {
        throw new NetIOException(e);
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestFSEditLogLoader.java

/**
 * Return the length of bytes in the given file after subtracting
 * the trailer of 0xFF (OP_INVALID)s./*from w  w w  .  j  a v  a 2s  . co m*/
 * This seeks to the end of the file and reads chunks backwards until
 * it finds a non-0xFF byte.
 * @throws IOException if the file cannot be read
 */
private static long getNonTrailerLength(File f) throws IOException {
    final int chunkSizeToRead = 256 * 1024;
    FileInputStream fis = new FileInputStream(f);
    try {

        byte buf[] = new byte[chunkSizeToRead];

        FileChannel fc = fis.getChannel();
        long size = fc.size();
        long pos = size - (size % chunkSizeToRead);

        while (pos >= 0) {
            fc.position(pos);

            int readLen = (int) Math.min(size - pos, chunkSizeToRead);
            IOUtils.readFully(fis, buf, 0, readLen);
            for (int i = readLen - 1; i >= 0; i--) {
                if (buf[i] != FSEditLogOpCodes.OP_INVALID.getOpCode()) {
                    return pos + i + 1; // + 1 since we count this byte!
                }
            }

            pos -= chunkSizeToRead;
        }
        return 0;
    } finally {
        fis.close();
    }
}

From source file:org.cloudata.core.commitlog.pipe.CommitLogFileChannel.java

public static long readLastIndex(FileChannel ch) throws IOException {
    ByteBuffer buf = ByteBuffer.allocate(Long.SIZE / 8);
    long chSize = ch.size();

    if (chSize > 0) {
        ch.position(chSize > (Long.SIZE / 8) ? chSize - (Long.SIZE / 8) : 0);
        ch.read(buf);/*w  w  w . j  a  v  a2s  . c  om*/
        buf.flip();
        return buf.getLong();
    } else {
        return 0;
    }
}

From source file:jext2.Superblock.java

/**
 * Read superblock using a FileChannel. This is intended for testing and code
 * that just needs the superblock not any file system access.
 *//*  w ww  .j a  v  a2 s . c o  m*/
public static Superblock fromFileChannel(FileChannel chan) throws IoError {

    Superblock sb = new Superblock(-1);
    ByteBuffer buf = ByteBuffer.allocate(Constants.EXT2_MIN_BLOCK_SIZE);
    try {
        chan.position(1024);
        chan.read(buf);
    } catch (IOException e) {
        throw new IoError();
    }
    sb.read(buf);

    Superblock.instance = sb;
    return sb;
}

From source file:io.undertow.server.handlers.SenderTestCase.java

@BeforeClass
public static void setup() {
    HttpHandler lotsOfSendsHandler = new HttpHandler() {
        @Override//w  w w. ja  va2s. c  om
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            boolean blocking = exchange.getQueryParameters().get("blocking").getFirst().equals("true");
            if (blocking) {
                if (exchange.isInIoThread()) {
                    exchange.startBlocking();
                    exchange.dispatch(this);
                    return;
                }
            }
            final Sender sender = exchange.getResponseSender();
            class SendClass implements Runnable, IoCallback {

                int sent = 0;

                @Override
                public void run() {
                    sent++;
                    sender.send("a", this);
                }

                @Override
                public void onComplete(final HttpServerExchange exchange, final Sender sender) {
                    if (sent++ == SENDS) {
                        sender.close();
                        return;
                    }
                    sender.send("a", this);
                }

                @Override
                public void onException(final HttpServerExchange exchange, final Sender sender,
                        final IOException exception) {
                    exception.printStackTrace();
                    exchange.endExchange();
                }
            }
            new SendClass().run();
        }
    };
    HttpHandler lotsOfTransferHandler = new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {

            boolean blocking = exchange.getQueryParameters().get("blocking").getFirst().equals("true");
            if (blocking) {
                if (exchange.isInIoThread()) {
                    exchange.startBlocking();
                    exchange.dispatch(this);
                    return;
                }
            }
            URI uri = SenderTestCase.class.getResource(SenderTestCase.class.getSimpleName() + ".class").toURI();
            Path file = Paths.get(uri);
            final FileChannel channel = FileChannel.open(file, StandardOpenOption.READ);

            exchange.setResponseContentLength(channel.size() * TXS);

            final Sender sender = exchange.getResponseSender();
            class SendClass implements Runnable, IoCallback {

                int sent = 0;

                @Override
                public void run() {
                    sent++;
                    try {
                        channel.position(0);
                    } catch (IOException e) {
                    }
                    sender.transferFrom(channel, this);
                }

                @Override
                public void onComplete(final HttpServerExchange exchange, final Sender sender) {
                    if (sent++ == TXS) {
                        sender.close();
                        return;
                    }
                    try {
                        channel.position(0);
                    } catch (IOException e) {
                    }
                    sender.transferFrom(channel, this);
                }

                @Override
                public void onException(final HttpServerExchange exchange, final Sender sender,
                        final IOException exception) {
                    exception.printStackTrace();
                    exchange.endExchange();
                }
            }
            new SendClass().run();
        }
    };

    final HttpHandler fixedLengthSender = new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            exchange.getResponseSender().send(HELLO_WORLD);
        }
    };

    PathHandler handler = new PathHandler().addPrefixPath("/lots", lotsOfSendsHandler)
            .addPrefixPath("/fixed", fixedLengthSender).addPrefixPath("/transfer", lotsOfTransferHandler);
    DefaultServer.setRootHandler(handler);
}