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:de.bund.bfr.pmfml.file.CombineArchiveUtil.java

static NuMLDocument readData(Path path) throws IOException, ParserConfigurationException, SAXException {
    try (InputStream is = Files.newInputStream(path, StandardOpenOption.READ)) {
        return NuMLReader.read(is);
    }//from www.  j a v  a 2 s .  c o  m
}

From source file:io.horizondb.io.files.DirectFileDataInput.java

/**
 * Creates a new <code>DirectFileDataInput</code> to read data from the specified file.
 * /*  w  w w .  j  a va  2  s .c  o  m*/
 * @param path the file path.
 * @param bufferSize the size of the buffer being used.
 */
public DirectFileDataInput(Path path, int bufferSize) throws IOException {

    notNull(path, "path parameter must not be null");
    isTrue(bufferSize > 0, "the buffer size must be greater than zero");

    this.channel = (FileChannel) Files.newByteChannel(path, StandardOpenOption.READ);

    this.buffer = ByteBuffer.allocateDirect(bufferSize);
    this.slice = Buffers.wrap(this.buffer);

    fillBuffer();
}

From source file:io.github.dsheirer.record.wave.MonoWaveReader.java

/**
 * Opens the file/*  w  w w  . ja v  a2s  .c o m*/
 */
private void open() throws IOException {
    if (!Files.exists(mPath)) {
        throw new IOException("File not found");
    }

    mInputStream = Files.newInputStream(mPath, StandardOpenOption.READ);

    //Check for RIFF header
    byte[] buffer = new byte[4];
    mInputStream.read(buffer);

    if (!Arrays.equals(buffer, WaveUtils.RIFF_CHUNK)) {
        throw new IOException("File is not .wav format - missing RIFF chunk");
    }

    //Get file size
    mInputStream.read(buffer);
    int fileSize = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();

    //Check for WAVE format
    mInputStream.read(buffer);

    if (!Arrays.equals(buffer, WaveUtils.WAV_FORMAT)) {
        throw new IOException("File is not .wav format - missing WAVE format");
    }

    //Check for format chunk
    mInputStream.read(buffer);

    if (!Arrays.equals(buffer, WaveUtils.CHUNK_FORMAT)) {
        throw new IOException("File is not .wav format - missing format chunk");
    }

    //Get chunk size
    mInputStream.read(buffer);
    int chunkSize = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();

    //Get format
    mInputStream.read(buffer);

    ShortBuffer shortBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
    short format = shortBuffer.get();
    if (format != WaveUtils.PCM_FORMAT) {
        throw new IOException("File format not supported - expecting PCM format");
    }

    //Get number of channels
    short channels = shortBuffer.get();
    if (channels != 1) {
        throw new IOException("Unsupported channel count - mono audio only");
    }

    //Get samples per second
    mInputStream.read(buffer);
    int sampleRate = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();

    //Get bytes per second
    mInputStream.read(buffer);
    int bytesPerSecond = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();

    mInputStream.read(buffer);

    //Get frame size
    shortBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
    short frameSize = shortBuffer.get();
    if (frameSize != 2) {
        throw new IOException("PCM frame size not supported - expecting 2 bytes per frame");
    }

    //Get bits per sample
    short bitsPerSample = shortBuffer.get();
    if (bitsPerSample != 16) {
        throw new IOException("PCM sample size not supported - expecting 16 bits per sample");
    }

    mInputStream.read(buffer);

    if (!Arrays.equals(buffer, WaveUtils.CHUNK_DATA)) {
        throw new IOException("Unexpected chunk - expecting data chunk");
    }

    //Get data chunk size
    mInputStream.read(buffer);
    mDataByteSize = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();
}

From source file:de.bluepair.sci.client.SHAUtils.java

public static <T> Map<String, String> sha512(Path path, Predicate<T> gard, T testValue, long blockSizePref,
        boolean forceBlockSize) {

    if (Files.notExists(path)) {
        return null;
    }//from   ww w.  java 2  s  .  c om
    MessageDigest md = getDigest();
    MessageDigest md1 = getDigest();

    if (!gard.test(testValue)) {
        return null;
    }
    long blockSize = blockSizePref;
    long size = -1;
    try {
        size = Files.size(path);
        if (!forceBlockSize) {// maximal 10 hashsummen
            // sonst hab ich zu viele in der datei
            // stehen!
            while (size / blockSize > 10) {
                blockSize += blockSizePref;
            }
        }

    } catch (IOException e) {
        blockSize = blockSizePref;
        return null;
    }

    Map<String, String> map = new HashMap<>();

    long lastStart = 0;

    long stepDown = blockSize;

    try (final SeekableByteChannel fileChannel = Files.newByteChannel(path, StandardOpenOption.READ);) {

        final ByteBuffer buffer = ByteBuffer.allocateDirect(8192);
        int last;
        do {
            if (!gard.test(testValue) || Files.notExists(path)) {
                return null;
            }
            buffer.clear();
            last = fileChannel.read(buffer);

            buffer.flip();
            md.update(buffer);

            // calc 2checksups
            buffer.flip();
            md1.update(buffer);

            if (last > 0) {
                stepDown -= last;
            }

            // wenn ich ein 100mb netzwerk habe
            // ~ca. 5MB bertragung
            // also bei abbruch kann wiederaufgesetzt werden wenn die summen
            // bekannt sind.
            // ~hnlich Blcke berechen also
            // 0-5 c1
            // 0-10 c2
            // 5-10 c3 ...

            if (stepDown <= 0 || (last <= 0)) {
                long len = (blockSize + Math.abs(stepDown));
                if (stepDown > 0) {
                    // kottektur wenn last <0
                    len = blockSize - stepDown;
                }
                stepDown = blockSize;
                map.put("sha512_" + lastStart + "_" + len, Hex.encodeHexString(md1.digest()));
                lastStart += len;
                md1.reset();
            }

        } while (last > 0);

    } catch (IOException ex) {
        Logger.getLogger(FileAnalysis.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }

    final byte[] sha1hash = md.digest();
    map.put("sha512", Hex.encodeHexString(sha1hash));
    return map;

}

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 {/* ww w . j a  v a 2 s. c  o  m*/
            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.ui.settings.SettingsProvider.java

@Override
public Settings get() {
    final Settings settings = new Settings(this::scheduleSave);
    try {//  w w w.j av  a 2s . c o m
        final Path settingsPath = getSettingsPath();
        final InputStream in = Files.newInputStream(settingsPath, StandardOpenOption.READ);
        objectMapper.readerForUpdating(settings).readValue(in);
        LOG.info("Settings loaded from " + settingsPath);
    } catch (IOException e) {
        LOG.info("Failed to load settings, creating new one.");
    }
    return settings;
}

From source file:com.cate.javatransmitter.FileHandler.java

public void setFile(Path inputPath) {
    //TODO add file selection
    this.inputPath = inputPath;
    try {/* ww  w . j  a v a  2  s  .  c om*/
        this.sbc = Files.newByteChannel(inputPath, StandardOpenOption.READ);
        this.nofChunks = (int) Math.ceil((double) (sbc.size()) / packetSize);
        System.out.println("File Size = " + sbc.size() + " Bytes");
        System.out.println("File Size = " + sbc.size() + " Bytes");
    } catch (IOException ex) {
        Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(0);
    }
    this.chunkCounter = 0;
    buf = ByteBuffer.allocate(packetSize);

    //catch (IOException x) {
    //    System.out.println("caught exception: " + x);        
    //        return null;
    //    }        
    //            
}

From source file:org.apache.nifi.minifi.FlowParser.java

/**
 * Generates a {@link Document} from the flow configuration file provided
 *///from  w ww . j av a 2 s  . com
public Document parse(final File flowConfigurationFile) {
    if (flowConfigurationFile == null) {
        logger.debug("Flow Configuration file was null");
        return null;
    }

    // if the flow doesn't exist or is 0 bytes, then return null
    final Path flowPath = flowConfigurationFile.toPath();
    try {
        if (!Files.exists(flowPath) || Files.size(flowPath) == 0) {
            logger.warn("Flow Configuration does not exist or was empty");
            return null;
        }
    } catch (IOException e) {
        logger.error("An error occurred determining the size of the Flow Configuration file");
        return null;
    }

    // otherwise create the appropriate input streams to read the file
    try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ);
            final InputStream gzipIn = new GZIPInputStream(in)) {

        final byte[] flowBytes = IOUtils.toByteArray(gzipIn);
        if (flowBytes == null || flowBytes.length == 0) {
            logger.warn("Could not extract root group id because Flow Configuration File was empty");
            return null;
        }

        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        // parse the flow
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new LoggingXmlParserErrorHandler("Flow Configuration", logger));
        final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes));
        return document;

    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex });
        return null;
    }
}

From source file:de.bund.bfr.pmfml.file.CombineArchiveUtil.java

static SBMLDocument readModel(Path path) throws IOException, XMLStreamException {
    try (InputStream stream = Files.newInputStream(path, StandardOpenOption.READ)) {
        return READER.readSBMLFromStream(stream);
    }/*  w w  w.  j  ava 2s. c  o m*/
}

From source file:org.apache.nifi.authorization.FlowParser.java

/**
 * Extracts the root group id from the flow configuration file provided in nifi.properties, and extracts
 * the root group input ports and output ports, and their access controls.
 *
 *//*from  w w  w.  j av a 2s  .c  o m*/
public FlowInfo parse(final File flowConfigurationFile) {
    if (flowConfigurationFile == null) {
        logger.debug("Flow Configuration file was null");
        return null;
    }

    // if the flow doesn't exist or is 0 bytes, then return null
    final Path flowPath = flowConfigurationFile.toPath();
    try {
        if (!Files.exists(flowPath) || Files.size(flowPath) == 0) {
            logger.warn("Flow Configuration does not exist or was empty");
            return null;
        }
    } catch (IOException e) {
        logger.error("An error occurred determining the size of the Flow Configuration file");
        return null;
    }

    // otherwise create the appropriate input streams to read the file
    try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ);
            final InputStream gzipIn = new GZIPInputStream(in)) {

        final byte[] flowBytes = IOUtils.toByteArray(gzipIn);
        if (flowBytes == null || flowBytes.length == 0) {
            logger.warn("Could not extract root group id because Flow Configuration File was empty");
            return null;
        }

        // create validating document builder
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setSchema(flowSchema);

        // parse the flow
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes));

        // extract the root group id
        final Element rootElement = document.getDocumentElement();

        final Element rootGroupElement = (Element) rootElement.getElementsByTagName("rootGroup").item(0);
        if (rootGroupElement == null) {
            logger.warn("rootGroup element not found in Flow Configuration file");
            return null;
        }

        final Element rootGroupIdElement = (Element) rootGroupElement.getElementsByTagName("id").item(0);
        if (rootGroupIdElement == null) {
            logger.warn("id element not found under rootGroup in Flow Configuration file");
            return null;
        }

        final String rootGroupId = rootGroupIdElement.getTextContent();

        final List<PortDTO> ports = new ArrayList<>();
        ports.addAll(getPorts(rootGroupElement, "inputPort"));
        ports.addAll(getPorts(rootGroupElement, "outputPort"));

        return new FlowInfo(rootGroupId, ports);

    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex });
        return null;
    }
}