Example usage for java.nio.file StandardOpenOption CREATE

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

Introduction

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

Prototype

StandardOpenOption CREATE

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

Click Source Link

Document

Create a new file if it does not exist.

Usage

From source file:com.gmt2001.datastore.IniStore.java

private void SaveFile(String fName, IniFile data) {
    if (data == null) {
        return;/*ww  w.  j a  v  a2 s . c  o  m*/
    }

    try {
        String wdata = "";
        Object[] adata = data.data.keySet().toArray();
        Object[] akdata;
        Object[] avdata;

        for (int i = 0; i < adata.length; i++) {
            if (i > 0) {
                wdata += "\r\n";
            }

            if (!((String) adata[i]).equals("")) {
                wdata += "[" + ((String) adata[i]) + "]\r\n";
            }

            akdata = data.data.get(((String) adata[i])).keySet().toArray();
            avdata = data.data.get(((String) adata[i])).values().toArray();

            for (int b = 0; b < akdata.length; b++) {
                wdata += ((String) akdata[b]) + "=" + ((String) avdata[b]) + "\r\n";
            }
        }
        if (!Files.isDirectory(Paths.get("./" + inifolder + "/"))) {
            Files.createDirectory(Paths.get("./" + inifolder + "/"));
        }

        Files.write(Paths.get("./" + inifolder + "/" + fName + ".ini"), wdata.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

        changed.remove(fName);
    } catch (IOException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }
}

From source file:org.epics.archiverappliance.etl.ZeroByteFilesTest.java

public void testZeroByteFileInDest() throws Exception {
    String pvName = ConfigServiceForTests.ARCH_UNIT_TEST_PVNAME_PREFIX + "ETL_testZeroDest";
    // Create an zero byte file in the ETL dest
    VoidFunction zeroByteGenerator = () -> {
        Path zeroDestPath = Paths.get(etlDest.getRootFolder(), pvNameToKeyConverter.convertPVNameToKey(pvName)
                + currentYear + PlainPBStoragePlugin.PB_EXTENSION);
        logger.info("Creating zero byte file " + zeroDestPath);
        Files.write(zeroDestPath, new byte[0], StandardOpenOption.CREATE);
    };/*from   w  ww .  j  a  va  2  s . c  o m*/
    runETLAndValidate(pvName, zeroByteGenerator);
}

From source file:org.kalypso.grid.BinaryGeoGrid.java

/**
 * Crates a new grid file with the given size and scale.<br>
 * The grid is then opened in write mode, so its values can then be set.<br>
 * The grid must be disposed afterwards in order to flush the written information. *
 * // w  ww .  j a v  a2s.  c  o  m
 * @param fillGrid
 *          If set to <code>true</code>, the grid will be initially filled with no-data values. Else, the grid values
 *          are undetermined.
 */
public static BinaryGeoGrid createGrid(final File file, final int sizeX, final int sizeY, final int scale,
        final Coordinate origin, final Coordinate offsetX, final Coordinate offsetY, final String sourceCRS,
        final boolean fillGrid) throws GeoGridException {
    try {
        final FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.READ,
                StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
        return new BinaryGeoGrid(channel, sizeX, sizeY, scale, origin, offsetX, offsetY, sourceCRS, fillGrid);
    } catch (final IOException e) {
        throw new GeoGridException("Could not find binary grid file: " + file.getAbsolutePath(), e);
    }
}

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

/**
 * Writes a given XML Flow out to the specified path.
 *
 * @param flowDocument flowDocument of the associated XML content to write to disk
 * @param flowXmlPath  path on disk to write the flow
 * @throws IOException if there are issues in accessing the target destination for the flow
 * @throws TransformerException if there are issues in the xml transformation process
 *//*ww  w.  jav a  2  s .  c o  m*/
public void writeFlow(final Document flowDocument, final Path flowXmlPath)
        throws IOException, TransformerException {
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final Source xmlSource = new DOMSource(flowDocument);
    final Result outputTarget = new StreamResult(outputStream);
    TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
    final InputStream is = new ByteArrayInputStream(outputStream.toByteArray());

    try (final OutputStream output = Files.newOutputStream(flowXmlPath, StandardOpenOption.WRITE,
            StandardOpenOption.CREATE); final OutputStream gzipOut = new GZIPOutputStream(output);) {
        FileUtils.copy(is, gzipOut);
    }
}

From source file:com.github.jinahya.simple.file.back.LocalFileBackTest.java

@Test(enabled = true, invocationCount = 1)
public void copy() throws IOException, FileBackException {

    fileContext.fileOperationSupplier(() -> FileOperation.COPY);

    final ByteBuffer sourceFileKey = randomFileKey();
    fileContext.sourceKeySupplier(() -> sourceFileKey);

    final ByteBuffer targetFileKey = randomFileKey();
    fileContext.targetKeySupplier(() -> targetFileKey);

    final Path sourceLeafPath = LocalFileBack.leafPath(rootPath, sourceFileKey, true);

    final byte[] fileBytes = randomFileBytes();
    final boolean fileWritten = Files.isRegularFile(sourceLeafPath) || current().nextBoolean();
    if (fileWritten) {
        Files.write(sourceLeafPath, fileBytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        logger.trace("file written");
    }//w ww.  j av  a  2  s .c  om

    fileBack.operate(fileContext);
}

From source file:org.apache.druid.segment.loading.LocalDataSegmentPusher.java

private DataSegment createDescriptorFile(DataSegment segment, File dest) throws IOException {
    log.info("Creating descriptor file at[%s]", dest);
    // Avoid using Guava in DataSegmentPushers because they might be used with very diverse Guava versions in
    // runtime, and because Guava deletes methods over time, that causes incompatibilities.
    Files.write(dest.toPath(), jsonMapper.writeValueAsBytes(segment), StandardOpenOption.CREATE,
            StandardOpenOption.SYNC);

    return segment;
}

From source file:uk.dsxt.voting.common.cryptoVote.CryptoVoteAcceptorWeb.java

private void sendNextVote() {
    if (!isNetworkOn)
        return;//from ww  w. j a  v  a 2 s  .  c o  m
    Map<String, String> parameters = unsentVoteMessages.poll();
    int queueSize = unsentVoteMessages.size();
    if (parameters == null)
        return;

    String result;
    try {
        result = httpHelper.request(acceptVoteUrl, parameters, RequestType.POST);
    } catch (IOException e) {
        log.warn("sendNextVote failed. url={} error={}", acceptVoteUrl, e);
        unsentVoteMessages.add(parameters);
        return;
    } catch (InternalLogicException e) {
        log.error("sendNextVote failed. url={}", acceptVoteUrl, e);
        unsentVoteMessages.add(parameters);
        return;
    }
    if (result == null || result.isEmpty()) {
        log.error("sendNextVote. result == null. url={}", acceptVoteUrl);
        unsentVoteMessages.add(parameters);
        return;
    }

    if (receiptsFile != null) {
        synchronized (receiptsFile) {
            try {
                Files.write(receiptsFile.toPath(), Collections.singletonList(result), Charset.forName("utf-8"),
                        StandardOpenOption.APPEND, StandardOpenOption.CREATE);
            } catch (IOException e) {
                log.warn("sendNextVote. Couldn't save result to file: {}. result='{}' error={}",
                        receiptsFile.getAbsolutePath(), result, e.getMessage());
            }
        }
    }
    try {
        NodeVoteReceipt receipt = mapper.readValue(result, NodeVoteReceipt.class);
        log.debug(
                "sendNextVote. Vote sent, receipt.status={} clientPacketResidual={} packetSize={} queueSize={}",
                receipt.getStatus(), parameters.get("clientPacketResidual"), parameters.get("packetSize"),
                queueSize);
    } catch (IOException e) {
        log.error("sendNextVote. can not read receipt {}. error={}", result, e.getMessage());
    }
}

From source file:at.ac.tuwien.infosys.util.ImageUtil.java

private void saveFile(URL url, Path file) throws IOException {
    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
    FileChannel channel = FileChannel.open(file, EnumSet.of(StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE));
    channel.transferFrom(rbc, 0, Long.MAX_VALUE);
    channel.close();//from   w  ww . ja  v a  2s  . c  om
}

From source file:com.netflix.genie.web.services.impl.DiskJobFileServiceImpl.java

/**
 * {@inheritDoc}//from www.  ja va  2s  . com
 */
@Override
// TODO: We should be careful about how large the byte[] is. Perhaps we should have precondition to protect memory
//       or we should wrap calls to this in something that chunks it off an input stream or just take this in as
//       input stream
public void updateFile(final String jobId, final String relativePath, final long startByte, final byte[] data)
        throws IOException {
    log.debug("Attempting to write {} bytes from position {} into log file {} for job {}", data.length,
            startByte, relativePath, jobId);
    final Path jobFile = this.jobsDirRoot.resolve(jobId).resolve(relativePath);

    if (Files.notExists(jobFile)) {
        // Make sure all the directories exist on disk
        final Path logFileParent = jobFile.getParent();
        if (logFileParent != null) {
            this.createOrCheckDirectory(logFileParent);
        }
    } else if (Files.isDirectory(jobFile)) {
        // TODO: Perhaps this should be different exception
        throw new IllegalArgumentException(relativePath + " is a directory not a file. Unable to update");
    }

    try (FileChannel fileChannel = FileChannel.open(jobFile,
            EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.SPARSE))) {
        // Move the byteChannel to the start byte
        fileChannel.position(startByte);

        // The size and length are ignored in this implementation as we just assume we're writing everything atm
        // TODO: Would it be better to provide an input stream and buffer the output?
        final ByteBuffer byteBuffer = ByteBuffer.wrap(data);

        while (byteBuffer.hasRemaining()) {
            fileChannel.write(byteBuffer);
        }
    }
}

From source file:ubicrypt.core.Utils.java

public static Observable<Long> write(final Path fullPath, final InputStream inputStream) {
    return Observable.create(subscriber -> {
        try {/* ww  w .jav  a  2s.  co m*/
            final AtomicLong offset = new AtomicLong(0);
            final AsynchronousFileChannel afc = AsynchronousFileChannel.open(fullPath, StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE);
            afc.lock(new Object(), new CompletionHandler<FileLock, Object>() {
                @Override
                public void completed(final FileLock lock, final Object attachment) {
                    //acquired lock
                    final byte[] buf = new byte[1 << 16];
                    try {
                        final int len = inputStream.read(buf);
                        if (len == -1) {
                            unsubscribe(subscriber, inputStream, lock);
                            return;
                        }
                        afc.write(ByteBuffer.wrap(Arrays.copyOfRange(buf, 0, len)), offset.get(), null,
                                new CompletionHandler<Integer, Object>() {
                                    @Override
                                    public void completed(final Integer result, final Object attachment) {
                                        //written chunk of bytes
                                        subscriber.onNext(offset.addAndGet(result));
                                        final byte[] buf = new byte[1 << 16];
                                        int len;
                                        try {
                                            len = inputStream.read(buf);
                                            if (len == -1) {
                                                unsubscribe(subscriber, inputStream, lock);
                                                log.debug("written:{}", fullPath);
                                                return;
                                            }
                                        } catch (final IOException e) {
                                            subscriber.onError(e);
                                            return;
                                        }
                                        if (len == -1) {
                                            unsubscribe(subscriber, inputStream, lock);
                                            log.debug("written:{}", fullPath);
                                            return;
                                        }
                                        afc.write(ByteBuffer.wrap(Arrays.copyOfRange(buf, 0, len)),
                                                offset.get(), null, this);
                                    }

                                    @Override
                                    public void failed(final Throwable exc, final Object attachment) {
                                        subscriber.onError(exc);
                                    }
                                });
                    } catch (final Exception e) {
                        close(inputStream, lock);
                        subscriber.onError(e);
                    }
                }

                @Override
                public void failed(final Throwable exc, final Object attachment) {
                    log.error("error on getting lock for:{}, error:{}", fullPath, exc.getMessage());
                    try {
                        inputStream.close();
                    } catch (final IOException e) {
                    }
                    subscriber.onError(exc);
                }
            });

        } catch (final Exception e) {
            log.error("error on file:{}", fullPath);
            subscriber.onError(e);
        }
    });
}