Example usage for java.nio.file StandardOpenOption READ

List of usage examples for java.nio.file StandardOpenOption READ

Introduction

In this page you can find the example usage for java.nio.file StandardOpenOption READ.

Prototype

StandardOpenOption READ

To view the source code for java.nio.file StandardOpenOption READ.

Click Source Link

Document

Open for read access.

Usage

From source file:ubicrypt.core.Utils.java

public static Observable<byte[]> read(final Path path) {
    return Observable.create(subscriber -> {
        final AtomicLong pos = new AtomicLong(0);
        try {/*from  w w  w  .  ja v  a  2 s . com*/
            final AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
            read(pos, ByteBuffer.allocate(1 << 16), channel, subscriber);
        } catch (final Throwable e) {
            subscriber.onError(e);
        }
    });
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public StreamContent download(String backendPath) throws C5CException {
    Path file = buildRealPath(backendPath);
    try {//from   w  w  w . j  a v  a 2 s. c o  m
        InputStream in = new BufferedInputStream(Files.newInputStream(file, StandardOpenOption.READ));
        return buildStreamContent(in, Files.size(file));
    } catch (FileNotFoundException e) {
        logger.error("Requested file not exits: {}", file.toAbsolutePath());
        throw new FilemanagerException(FilemanagerAction.DOWNLOAD, FilemanagerException.Key.FileNotExists,
                backendPath);
    } catch (IOException | SecurityException e) {
        String msg = String.format("Error while downloading {}: {}", file.getFileName().toFile(),
                e.getMessage());
        logger.error(msg, e);
        throw new C5CException(FilemanagerAction.DOWNLOAD, msg);
    }
}

From source file:nextflow.fs.dx.DxFileSystemProvider.java

public InputStream newInputStream(Path file, OpenOption... options) throws IOException {
    if (options.length > 0) {
        for (OpenOption opt : options) {
            if (opt != StandardOpenOption.READ)
                throw new UnsupportedOperationException("'" + opt + "' not allowed");
        }//from   w ww . j a  v a  2  s.  c o  m
    }

    final DxPath path = toDxPath(file);
    final String fileId = path.getFileId();
    final Map<String, Object> download = api.fileDownload(fileId);
    final String url = (String) download.get("url");
    final Map<String, String> headers = (Map<String, String>) download.get("headers");

    final HttpClient client = DxHttpClient.getInstance().http();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpGet get = new HttpGet(url);
    get.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
    for (Map.Entry<String, String> item : headers.entrySet()) {
        get.setHeader(item.getKey(), item.getValue());
    }

    return client.execute(get).getEntity().getContent();
}

From source file:schemacrawler.test.utility.TestUtility.java

private static Reader readerForFile(final Path testOutputTempFile, final boolean isCompressed)
        throws IOException {

    final BufferedReader bufferedReader;
    if (isCompressed) {
        final ZipInputStream inputStream = new ZipInputStream(
                newInputStream(testOutputTempFile, StandardOpenOption.READ));
        inputStream.getNextEntry();// w  w  w . j a  v  a 2 s .c  o  m

        bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
    } else {
        bufferedReader = newBufferedReader(testOutputTempFile, StandardCharsets.UTF_8);
    }
    return bufferedReader;
}

From source file:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java

private boolean isPathFullyAccessible(Path path) {
    if (!Files.exists(path)) {
        return false;
    }/* www  .ja  va 2s.c  om*/

    if (Files.isDirectory(path)) {
        DirectoryStream<Path> directoryStream = null;
        try {
            directoryStream = Files.newDirectoryStream(path);

            return true;
        } catch (IOException e) {
            log.debug("Unaccessible directory: {}", path, e);
            return false;
        } finally {
            IOUtils.closeQuietly(directoryStream);
        }

    } else {
        FileChannel fileChannel = null;
        try {
            fileChannel = FileChannel.open(path, StandardOpenOption.READ);
            fileChannel.position(Files.size(path));

            return true;
        } catch (IOException e) {
            log.debug("Unaccessible file: {}", path, e);
            return false;
        } finally {
            IOUtils.closeQuietly(fileChannel);
        }
    }
}

From source file:org.darkware.wpman.security.ChecksumDatabase.java

/**
 * Calculate a checksum on the given file.
 *
 * @param file The file to calculate a checksum for.
 * @return The checksum as a {@code String}.
 * @see #doChecksum(ReadableByteChannel)
 */// w  w w .  ja v a 2  s.c o  m
protected String calculateChecksum(final Path file) {
    try (FileChannel channel = FileChannel.open(file, StandardOpenOption.READ)) {
        return this.doChecksum(channel);
    } catch (IOException e) {
        ChecksumDatabase.log.error("Failed to calculate checksum on {}: {}", file, e.getLocalizedMessage());
        return "";
    }
}

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 {//from  w w w .java  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:org.craftercms.studio.impl.v1.repository.disk.DiskContentRepository.java

protected InputStream getVersionedContent(String path, String label) throws ContentNotFoundException {
    InputStream retStream = null;

    try {//w  w w .j av  a  2  s  .c o  m
        OpenOption options[] = { StandardOpenOption.READ };
        retStream = Files.newInputStream(constructVersionRepoPath(path + "--" + label));
    }

    catch (Exception err) {
        throw new ContentNotFoundException("error while opening file", err);
    }

    return retStream;
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public String editFile(String backendPath) throws C5CException {
    Path file = buildRealPath(backendPath);
    InputStream in = null;//from  w w  w. ja  v  a2  s  .c  o m
    try {
        in = Files.newInputStream(file, StandardOpenOption.READ);
        return IOUtils.toString(in, PropertiesLoader.getDefaultEncoding());
    } catch (IOException e) {
        throw new C5CException(FilemanagerAction.EDITFILE, e.getMessage());
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:com.clustercontrol.agent.log.LogfileMonitor.java

/**
 * ?//  w ww.  j ava  2  s.  co m
 */
private boolean openFile() {
    m_log.info("openFile : filename=" + status.rsFilePath.getName());

    closeFile();

    FileChannel fc = null;

    // 
    try {
        if (checkPrefix())
            status.rotate();

        fc = FileChannel.open(Paths.get(getFilePath()), StandardOpenOption.READ);

        long filesize = fc.size();
        if (filesize > LogfileMonitorConfig.fileMaxSize) {
            // ????????
            // message.log.agent.1={0}?
            // message.log.agent.3=??????
            // message.log.agent.5={0} byte?
            String[] args1 = { getFilePath() };
            String[] args2 = { String.valueOf(filesize) };
            sendMessage(PriorityConstant.TYPE_INFO, MessageConstant.AGENT.getMessage(),
                    MessageConstant.MESSAGE_LOG_FILE_SIZE_EXCEEDED_UPPER_BOUND.getMessage(),
                    MessageConstant.MESSAGE_LOG_FILE.getMessage(args1) + ", "
                            + MessageConstant.MESSAGE_LOG_FILE_SIZE_BYTE.getMessage(args2));
        }

        // ??
        // ?open?init=true??
        // ??open?init=false???
        fc.position(status.position);

        fileChannel = fc;

        return true;
    } catch (FileNotFoundException e) {
        m_log.info("openFile : " + e.getMessage());
        if (m_initFlag) {
            // ????????
            // message.log.agent.1={0}?
            // message.log.agent.2=???????
            String[] args = { getFilePath() };
            sendMessage(PriorityConstant.TYPE_INFO, MessageConstant.AGENT.getMessage(),
                    MessageConstant.MESSAGE_LOG_FILE_NOT_FOUND.getMessage(),
                    MessageConstant.MESSAGE_LOG_FILE.getMessage(args));
        }

        return false;
    } catch (SecurityException e) {
        m_log.info("openFile : " + e.getMessage());
        if (m_initFlag) {
            // ??
            // message.log.agent.1={0}?
            // message.log.agent.4=????????
            String[] args = { getFilePath() };
            sendMessage(PriorityConstant.TYPE_WARNING, MessageConstant.AGENT.getMessage(),
                    MessageConstant.MESSAGE_LOG_FAILED_TO_READ_FILE.getMessage(),
                    MessageConstant.MESSAGE_LOG_FILE.getMessage(args) + "\n" + e.getMessage());
        }
        return false;
    } catch (IOException e) {
        m_log.info("openFile : " + e.getMessage());
        if (m_initFlag) {
            // ??
            // message.log.agent.1={0}?
            // message.log.agent.4=????????
            String[] args = { getFilePath() };
            sendMessage(PriorityConstant.TYPE_INFO, MessageConstant.AGENT.getMessage(),
                    MessageConstant.MESSAGE_LOG_FAILED_TO_READ_FILE.getMessage(),
                    MessageConstant.MESSAGE_LOG_FILE.getMessage(args));
        }
        return false;
    } finally {
        // ??????????????
        if (fc != null && fileChannel == null) {
            try {
                fc.close();
            } catch (IOException e) {
                m_log.warn(e.getMessage(), e);
            }
        }
        m_initFlag = false;
    }
}