Example usage for java.nio.file Files newByteChannel

List of usage examples for java.nio.file Files newByteChannel

Introduction

In this page you can find the example usage for java.nio.file Files newByteChannel.

Prototype

public static SeekableByteChannel newByteChannel(Path path, OpenOption... options) throws IOException 

Source Link

Document

Opens or creates a file, returning a seekable byte channel to access the file.

Usage

From source file:com.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java

private void replaceFile(final Path file, final URL url) throws IOException {
    //Create the file
    SeekableByteChannel sbc = null;
    try {/*from  w  w w. j av a 2s  . co  m*/
        //Creates a new Readable Byte channel from URL
        final ReadableByteChannel rbc = Channels.newChannel(url.openStream());
        //Create the file
        sbc = Files.newByteChannel(file, FILE_REPLACE_OPTIONS);

        //Clears the buffer
        buffer.clear();

        //Read input Channel
        while (rbc.read(buffer) != -1) {
            // prepare the buffer to be drained
            buffer.flip();
            // write to the channel, may block
            sbc.write(buffer);
            // If partial transfer, shift remainder down
            // If buffer is empty, same as doing clear()
            buffer.compact();
        }
        // EOF will leave buffer in fill state
        buffer.flip();
        // make sure the buffer is fully drained.
        while (buffer.hasRemaining()) {
            sbc.write(buffer);
        }
    } finally {
        if (sbc != null) {
            sbc.close();
        }
    }
}

From source file:com.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java

/**
 * Writes file to disk and copy the contents of the input byte array.
 *
 * @param file     a Path with file path.
 * @param contents a byte[] with the contents
 * @throws IOException//from w w  w . j av a  2s.c o  m
 */
private void writeFile(final Path file, final byte[] contents) throws IOException {
    final ByteBuffer bb = ByteBuffer.wrap(contents);
    //Create the file
    final SeekableByteChannel sbc = Files.newByteChannel(file, FILE_OPEN_OPTIONS);
    //Copy contents to the new File
    sbc.write(bb);
    //Close the byte channel
    sbc.close();
}

From source file:com.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java

private void replaceFile(final Path file, final byte[] contents) throws IOException {
    final ByteBuffer bb = ByteBuffer.wrap(contents);
    //Create the file
    final SeekableByteChannel sbc = Files.newByteChannel(file, FILE_REPLACE_OPTIONS);
    //Copy contents to the new File
    sbc.write(bb);//w  w w  . ja  v a  2 s.c o  m
    //Close the byte channel
    sbc.close();
}

From source file:com.arpnetworking.tsdcore.tailer.StatefulTailer.java

private Optional<Boolean> compareByHash(final Optional<String> prefixHash, final int prefixLength) {
    final int appliedLength;
    if (_hash.isPresent()) {
        appliedLength = REQUIRED_BYTES_FOR_HASH;
    } else {/*  w ww.  j a va  2 s .c o m*/
        appliedLength = prefixLength;
    }
    try (final SeekableByteChannel reader = Files.newByteChannel(_file.toPath(), StandardOpenOption.READ)) {
        final Optional<String> filePrefixHash = computeHash(reader, appliedLength);

        LOGGER.trace(String.format("Comparing hashes; hash1=%s, hash2=%s, size=%d", prefixHash, filePrefixHash,
                Integer.valueOf(appliedLength)));

        return Optional
                .of(Boolean.valueOf(Objects.equals(_hash.or(prefixHash).orNull(), filePrefixHash.orNull())));
    } catch (final IOException e) {
        return Optional.absent();
    }
}

From source file:com.arpnetworking.metrics.common.tailer.StatefulTailer.java

private Optional<Boolean> compareByHash(final Optional<String> prefixHash, final int prefixLength) {
    final int appliedLength;
    if (_hash.isPresent()) {
        appliedLength = REQUIRED_BYTES_FOR_HASH;
    } else {/*from   w  w  w .  j a va2  s.  c om*/
        appliedLength = prefixLength;
    }
    try (final SeekableByteChannel reader = Files.newByteChannel(_file, StandardOpenOption.READ)) {
        final Optional<String> filePrefixHash = computeHash(reader, appliedLength);

        LOGGER.trace().setMessage("Comparing hashes").addData("hash1", prefixHash)
                .addData("filePrefixHash", filePrefixHash).addData("size", appliedLength).log();

        return Optional.of(Objects.equals(_hash.orElse(prefixHash.orElse(null)), filePrefixHash.orElse(null)));
    } catch (final IOException e) {
        return Optional.empty();
    }
}

From source file:org.cryptomator.webdav.jackrabbit.resources.EncryptedFile.java

@Override
public void spool(OutputContext outputContext) throws IOException {
    final Path path = ResourcePathUtils.getPhysicalPath(this);
    if (Files.exists(path)) {
        outputContext.setModificationTime(Files.getLastModifiedTime(path).toMillis());
        outputContext.setProperty(HttpHeader.ACCEPT_RANGES.asString(), HttpHeaderValue.BYTES.asString());
        SeekableByteChannel channel = null;
        try {//from   www  . j  av  a2 s  .c  om
            channel = Files.newByteChannel(path, StandardOpenOption.READ);
            if (checkIntegrity && !cryptor.authenticateContent(channel)) {
                throw new DecryptFailedException("File content compromised: " + path.toString());
            }
            outputContext.setContentLength(cryptor.decryptedContentLength(channel));
            if (outputContext.hasStream()) {
                cryptor.decryptedFile(channel, outputContext.getOutputStream());
            }
        } catch (EOFException e) {
            LOG.warn("Unexpected end of stream (possibly client hung up).");
        } catch (DecryptFailedException e) {
            throw new IOException("Error decrypting file " + path.toString(), e);
        } finally {
            IOUtils.closeQuietly(channel);
        }
    }
}

From source file:org.cryptomator.webdav.jackrabbit.resources.EncryptedFile.java

@Override
protected void determineProperties() {
    final Path path = ResourcePathUtils.getPhysicalPath(this);
    if (Files.exists(path)) {
        SeekableByteChannel channel = null;
        try {/*  w w w. j  a  v  a2 s.c  o  m*/
            channel = Files.newByteChannel(path, StandardOpenOption.READ);
            final Long contentLength = cryptor.decryptedContentLength(channel);
            properties.add(new DefaultDavProperty<Long>(DavPropertyName.GETCONTENTLENGTH, contentLength));

            final BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
            properties.add(new DefaultDavProperty<String>(DavPropertyName.CREATIONDATE,
                    FileTimeUtils.toRfc1123String(attrs.creationTime())));
            properties.add(new DefaultDavProperty<String>(DavPropertyName.GETLASTMODIFIED,
                    FileTimeUtils.toRfc1123String(attrs.lastModifiedTime())));
            properties.add(new HttpHeaderProperty(HttpHeader.ACCEPT_RANGES.asString(),
                    HttpHeaderValue.BYTES.asString()));
        } catch (IOException e) {
            LOG.error("Error determining metadata " + path.toString(), e);
            throw new IORuntimeException(e);
        } finally {
            IOUtils.closeQuietly(channel);
        }
    }
}

From source file:org.silverpeas.core.web.http.FileResponse.java

/**
 * Fills partially the output response.//from w  w  w.j  ava2 s .c o  m
 * @param path the path of the file.
 * @param partialData the partial data.
 * @param output the output stream to write into.
 */
void partialOutputStream(final Path path, final ContentRangeData partialData, final OutputStream output)
        throws IOException {
    SilverLogger.getLogger(this).debug("{0} - start at {1} - end at {2} - partLength {3}",
            StringUtil.abbreviate(path.toString(), path.toString().length(), MAX_PATH_LENGTH_IN_LOGS),
            partialData.start, partialData.end, partialData.partContentLength);
    try (SeekableByteChannel input = Files.newByteChannel(path, READ)) {
        input.position(partialData.start);
        int bytesRead;
        int bytesLeft = partialData.partContentLength;
        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_LENGTH);
        while ((bytesRead = input.read(buffer)) != -1 && bytesLeft > 0) {
            buffer.clear();
            output.write(buffer.array(), 0, bytesLeft < bytesRead ? bytesLeft : bytesRead);
            bytesLeft -= bytesRead;
        }
        SilverLogger.getLogger(this).debug("{0} - all part content bytes sent",
                StringUtil.abbreviate(path.toString(), path.toString().length(), MAX_PATH_LENGTH_IN_LOGS));
    } catch (IOException ioe) {
        SilverLogger.getLogger(this).debug(
                "client stopping the streaming HTTP Request of file content represented by "
                        + "''{0}'' identifier (original message ''{1}'')",
                StringUtil.abbreviate(path.toString(), path.toString().length(), MAX_PATH_LENGTH_IN_LOGS),
                ioe.getMessage(), ioe);
    }
}

From source file:sf.net.experimaestro.fs.XPMFileSystemProvider.java

@Override
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options,
        FileAttribute<?>... attrs) throws IOException {
    final Path hostPathObject = resolvePath((XPMPath) path);

    SeekableByteChannel channel = Files.newByteChannel(hostPathObject, StandardOpenOption.READ);
    if (channel == null) {
        throw new IOException(format("Could not find a valid mount point for %s", path));
    }/*from w  w w . jav a 2s . c om*/

    return channel;
}

From source file:srebrinb.compress.sevenzip.SevenZFile.java

/**
 * Reads a file as 7z archive/*  w w  w  .j a  v  a2 s. c o  m*/
 *
 * @param filename the file to read
 * @param password optional password if the archive is encrypted -
 * the byte array is supposed to be the UTF16-LE encoded
 * representation of the password.
 * @throws IOException if reading the archive fails
 */
public SevenZFile(final File filename, final byte[] password) throws IOException {
    this(Files.newByteChannel(filename.toPath(), EnumSet.of(StandardOpenOption.READ)),
            filename.getAbsolutePath(), password, true);
}