Example usage for java.nio.file StandardOpenOption WRITE

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

Introduction

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

Prototype

StandardOpenOption WRITE

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

Click Source Link

Document

Open for write access.

Usage

From source file:org.eclipse.jgit.lfs.server.fs.LfsServerTest.java

protected long getContent(String hexId, Path f) throws IOException {
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpGet request = new HttpGet(server.getURI() + "/lfs/objects/" + hexId);
        HttpResponse response = client.execute(request);
        checkResponseStatus(response);/*from   www  .  j a va 2  s.  c  o  m*/
        HttpEntity entity = response.getEntity();
        long pos = 0;
        try (InputStream in = entity.getContent();
                ReadableByteChannel inChannel = Channels.newChannel(in);
                FileChannel outChannel = FileChannel.open(f, StandardOpenOption.CREATE_NEW,
                        StandardOpenOption.WRITE)) {
            long transferred;
            do {
                transferred = outChannel.transferFrom(inChannel, pos, MiB);
                pos += transferred;
            } while (transferred > 0);
        }
        return pos;
    }
}

From source file:org.apache.nifi.controller.TemplateManager.java

/**
 * Persists the given template to disk/*from  w ww  . j  av a2s  . c o  m*/
 *
 * @param template template
 * @throws IOException ioe
 */
private void persistTemplate(final Template template) throws IOException {
    final Path path = directory.resolve(template.getDetails().getId() + ".template");
    Files.write(path, TemplateSerializer.serialize(template.getDetails()), StandardOpenOption.WRITE,
            StandardOpenOption.CREATE);
}

From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java

private void replaceVariables(ServletContext context, List<CssAttribute> cssAttributes, String FILE_NAME,
        File destDir) throws IOException {
    InputStream lessIs = context.getResourceAsStream(FILE_NAME);
    Path outputPath = new File(destDir, FILE_NAME).toPath();
    String content = IOUtils.toString(lessIs, Constants.UTF8);
    for (CssAttribute attribute : cssAttributes) {
        if (!StringUtils.isEmpty(attribute.getCssValue())) {
            content = content.replaceAll(attribute.getCssDefaultValue(), attribute.getCssValue());
        }/*  ww w .  j  ava2  s .  c om*/
    }

    //overwrite variables.less in data directory
    if (!Files.exists(outputPath)) {
        if (!Files.exists(outputPath.getParent())) {
            Files.createDirectory(outputPath.getParent());
        }
        Files.createFile(outputPath);
    }
    Files.write(outputPath, content.getBytes(Constants.UTF8), StandardOpenOption.CREATE,
            StandardOpenOption.WRITE);
}

From source file:io.pravega.segmentstore.storage.impl.extendeds3.S3FileSystemImpl.java

@Synchronized
@Override/*from  ww  w .j av  a  2s.c o  m*/
public CompleteMultipartUploadResult completeMultipartUpload(CompleteMultipartUploadRequest request) {
    Map<Integer, CopyPartRequest> partMap = multipartUploads.get(request.getKey());
    if (partMap == null) {
        throw new S3Exception("NoSuchKey", HttpStatus.SC_NOT_FOUND, "NoSuchKey", "");
    }
    try {
        partMap.forEach((index, copyPart) -> {
            if (copyPart.getKey() != copyPart.getSourceKey()) {
                Path sourcePath = Paths.get(this.baseDir, copyPart.getBucketName(), copyPart.getSourceKey());
                Path targetPath = Paths.get(this.baseDir, copyPart.getBucketName(), copyPart.getKey());
                try (FileChannel sourceChannel = FileChannel.open(sourcePath, StandardOpenOption.READ);
                        FileChannel targetChannel = FileChannel.open(targetPath, StandardOpenOption.WRITE)) {
                    targetChannel.transferFrom(sourceChannel, Files.size(targetPath),
                            copyPart.getSourceRange().getLast() + 1 - copyPart.getSourceRange().getFirst());
                    targetChannel.close();
                    AclSize aclMap = this.aclMap.get(copyPart.getKey());
                    this.aclMap.put(copyPart.getKey(), aclMap.withSize(Files.size(targetPath)));
                } catch (IOException e) {
                    throw new S3Exception("NoSuchKey", 404, "NoSuchKey", "");
                }
            }
        });
    } finally {
        multipartUploads.remove(request.getKey());
    }

    return new CompleteMultipartUploadResult();
}

From source file:revisaoswing.FormCadastro.java

private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
    String nome = txtNome.getText();

    if (nome.isEmpty()) {
        JOptionPane.showMessageDialog(this, "Erro", "Nome no informado", JOptionPane.ERROR_MESSAGE);
        return;/*ww w  .  j  a v  a2  s. c om*/
    }
    String dataNasc = txtDtNasc.getText();
    String sexo = "f";
    if (rbMasc.isSelected()) {
        sexo = "m";
    }
    String funcao = cbFuncao.getSelectedItem().toString();
    boolean vt = ckbVT.isSelected();

    JSONObject obj = new JSONObject();
    obj.put("Nome", nome);
    obj.put("Data", dataNasc);
    obj.put("Sexo", sexo);
    obj.put("Funcao", funcao);
    obj.put("VT", vt);

    try {
        RevisaoSwing.carregarArray();
        RevisaoSwing.array.add(obj);

        byte[] bytes = RevisaoSwing.array.toJSONString().getBytes();
        Files.write(RevisaoSwing.arquivo, bytes, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
    } catch (IOException ex) {
        Logger.getLogger(FormCadastro.class.getName()).log(Level.SEVERE, null, ex);
    }

    JOptionPane.showMessageDialog(this, "Salvo com Sucesso!");

    txtNome.setText(null);
    txtDtNasc.setText(null);
    rbMasc.setSelected(true);
    ckbVT.setSelected(false);
    cbFuncao.setSelectedIndex(0);
}

From source file:org.eclipse.jgit.lfs.server.fs.LfsServerTest.java

/**
 * Creates a file with random content, repeatedly writing a random string of
 * 4k length to the file until the file has at least the specified length.
 *
 * @param f//from  w w w .j ava 2s. c  om
 *            file to fill
 * @param size
 *            size of the file to generate
 * @return length of the generated file in bytes
 * @throws IOException
 */
protected long createPseudoRandomContentFile(Path f, long size) throws IOException {
    SecureRandom rnd = new SecureRandom();
    byte[] buf = new byte[4096];
    rnd.nextBytes(buf);
    ByteBuffer bytebuf = ByteBuffer.wrap(buf);
    try (FileChannel outChannel = FileChannel.open(f, StandardOpenOption.CREATE_NEW,
            StandardOpenOption.WRITE)) {
        long len = 0;
        do {
            len += outChannel.write(bytebuf);
            if (bytebuf.position() == 4096) {
                bytebuf.rewind();
            }
        } while (len < size);
    }
    return Files.size(f);
}

From source file:org.basinmc.maven.plugins.bsdiff.DiffMojo.java

/**
 * Retrieves a remote artifact and stores it in a pre-defined cache directory.
 *///w ww . ja v a 2  s.  com
@Nonnull
private Path retrieveSourceFile() throws MojoFailureException {
    HttpClient client = HttpClients.createMinimal();
    String fileName;

    {
        String path = this.sourceURL.getPath();

        int i = path.lastIndexOf('/');
        fileName = path.substring(i + 1);
    }

    try {
        this.getLog().info("Downloading source artifact from " + this.sourceURL.toExternalForm());

        HttpGet request = new HttpGet(this.sourceURL.toURI());
        HttpResponse response = client.execute(request);

        if (response.containsHeader("Content-Disposition")) {
            String disposition = response.getLastHeader("Content-Disposition").getValue();
            Matcher matcher = DISPOSITION_PATTERN.matcher(disposition);

            if (matcher.matches()) {
                fileName = URLDecoder.decode(matcher.group(1), "UTF-8");
            }
        }

        this.getLog().info("Storing " + fileName + " in cache directory");
        Path outputPath = this.cacheDirectory.toPath().resolve(fileName);

        if (!Files.isDirectory(outputPath.getParent())) {
            Files.createDirectories(outputPath.getParent());
        }

        try (InputStream inputStream = response.getEntity().getContent()) {
            try (ReadableByteChannel inputChannel = Channels.newChannel(inputStream)) {
                try (FileChannel outputChannel = FileChannel.open(outputPath, StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
                    outputChannel.transferFrom(inputChannel, 0, Long.MAX_VALUE);
                }
            }
        }

        return outputPath;
    } catch (IOException ex) {
        throw new MojoFailureException("Failed to read/write source artifact: " + ex.getMessage(), ex);
    } catch (URISyntaxException ex) {
        throw new MojoFailureException("Invalid source URI: " + ex.getMessage(), ex);
    }
}

From source file:org.apache.kylin.cube.inmemcubing.ConcurrentDiskStore.java

private void openWriteChannel(long startOffset) throws IOException {
    if (startOffset > 0) { // TODO does not support append yet
        writeChannel = FileChannel.open(diskFile.toPath(), StandardOpenOption.CREATE, StandardOpenOption.APPEND,
                StandardOpenOption.WRITE);
    } else {// ww w  .jav  a 2 s.c  o  m
        diskFile.delete();
        writeChannel = FileChannel.open(diskFile.toPath(), StandardOpenOption.CREATE_NEW,
                StandardOpenOption.WRITE);
    }
}

From source file:com.diffplug.gradle.FileMisc.java

/** Concats the first files and writes them to the last file. */
public static void concat(Iterable<File> toMerge, File dst) throws IOException {
    try (FileChannel dstChannel = FileChannel.open(dst.toPath(), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
        for (File file : toMerge) {
            try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
                FileChannel channel = raf.getChannel();
                dstChannel.write(channel.map(FileChannel.MapMode.READ_ONLY, 0, raf.length()));
            }//from  ww  w.j a  v  a  2s  .  com
        }
    }
}

From source file:com.amazonaws.services.kinesis.producer.Daemon.java

private void connectToChild() throws IOException {
    long start = System.nanoTime();
    while (true) {
        try {/*from  ww  w.j  a v a2s .c om*/
            inChannel = FileChannel.open(Paths.get(inPipe.getAbsolutePath()), StandardOpenOption.READ);
            outChannel = FileChannel.open(Paths.get(outPipe.getAbsolutePath()), StandardOpenOption.WRITE);
            outStream = Channels.newOutputStream(outChannel);
            break;
        } catch (IOException e) {
            if (inChannel != null && inChannel.isOpen()) {
                inChannel.close();
            }
            if (outChannel != null && outChannel.isOpen()) {
                outChannel.close();
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
            }
            if (System.nanoTime() - start > 2e9) {
                throw e;
            }
        }
    }
}