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:org.cloudfoundry.dependency.resource.InAction.java

private void writeVersion() {
    try {//  ww w .  ja  va 2s.  c o m
        String version = new VersionHolder(this.request.getVersion().getRef()).toRepositoryVersion();
        Path versionFile = Files.createDirectories(this.destination).resolve("version");
        Files.write(versionFile, Collections.singletonList(version), StandardOpenOption.CREATE,
                StandardOpenOption.WRITE);
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }
}

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

@Test
public void testRelativeSymlink() throws IOException, URISyntaxException {
    assumeFalse(Platform.isWindows());//w w  w  .  j  av  a2  s .  c  o  m
    final Path tempDir = Files.createTempDirectory("ds3_file_object_rel_test_");
    final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt");

    try {
        try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(testData));
        }

        final Path symLinkPath = tempDir.resolve("sym_" + tempPath.getFileName().toString());
        final Path relPath = Paths.get("..", getParentDir(tempPath), tempPath.getFileName().toString());

        LOG.info("Creating symlink from " + symLinkPath.toString() + " to " + relPath.toString());

        Files.createSymbolicLink(symLinkPath, relPath);
        getFileWithPutter(tempDir, symLinkPath);

    } finally {
        Files.deleteIfExists(tempPath);
        Files.deleteIfExists(tempDir);
    }
}

From source file:org.cryptomator.frontend.webdav.servlet.DavFolder.java

private void addMemberFile(DavFile memberFile, InputStream inputStream) {
    try (ReadableByteChannel src = Channels.newChannel(inputStream); //
            WritableByteChannel dst = Files.newByteChannel(memberFile.path, StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
        ByteStreams.copy(src, dst);/*from w  w  w. ja v a 2  s  .  co m*/
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:divconq.util.IOUtil.java

public static boolean saveEntireFile2(Path dest, Memory content) {
    try {/*from   w ww .j  a  v  a2 s .c o m*/
        Files.createDirectories(dest.getParent());
        Files.write(dest, content.toArray(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING,
                StandardOpenOption.WRITE, StandardOpenOption.SYNC);
    } catch (Exception x) {
        return false;
    }

    return true;
}

From source file:io.apiman.common.es.util.ApimanEmbeddedElastic.java

private void deleteProcessId() throws IOException {
    if (Files.exists(pidPath)) {
        List<String> pidLines = Files.readAllLines(pidPath).stream()
                .filter(storedPid -> !storedPid.equalsIgnoreCase(String.valueOf(pid))) // Compare PID (long) with PID from file (String)
                .collect(Collectors.toList());
        // Write back with successfully terminated PID removed.
        Files.write(pidPath, pidLines, Charset.defaultCharset(), StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING);
    } else {//from  w  w w  .  j a v a  2s.c om
        System.err.println("No pid file. Did someone delete it while the program was running?");
    }
}

From source file:no.imr.stox.functions.acoustic.PgNapesIO.java

public static void export2(String cruise, String country, String callSignal, String path, String fileName,
        List<DistanceBO> distances, Double groupThickness, Integer freqFilter, String specFilter,
        boolean withZeros) {
    Set<Integer> freqs = distances.stream().flatMap(dist -> dist.getFrequencies().stream())
            .map(FrequencyBO::getFreq).collect(Collectors.toSet());
    if (freqFilter == null && freqs.size() == 1) {
        freqFilter = freqs.iterator().next();
    }//from  ww w .j av  a2  s .co  m

    if (freqFilter == null) {
        System.out.println("Multiple frequencies, specify frequency filter as parameter");
        return;
    }
    Integer freqFilterF = freqFilter; // ef.final
    List<String> acList = distances.parallelStream().flatMap(dist -> dist.getFrequencies().stream())
            .filter(fr -> freqFilterF.equals(fr.getFreq())).map(f -> {
                DistanceBO d = f.getDistanceBO();
                LocalDateTime sdt = LocalDateTime.ofInstant(d.getStart_time().toInstant(), ZoneOffset.UTC);
                Double intDist = d.getIntegrator_dist();
                String month = StringUtils.leftPad(sdt.getMonthValue() + "", 2, "0");
                String day = StringUtils.leftPad(sdt.getDayOfMonth() + "", 2, "0");
                String hour = StringUtils.leftPad(sdt.getHour() + "", 2, "0");
                String minute = StringUtils.leftPad(sdt.getMinute() + "", 2, "0");
                String log = Conversion.formatDoubletoDecimalString(d.getLog_start(), "0.0");
                String acLat = Conversion.formatDoubletoDecimalString(d.getLat_start(), "0.000");
                String acLon = Conversion.formatDoubletoDecimalString(d.getLon_start(), "0.000");
                return Stream
                        .of(d.getNation(), d.getPlatform(), d.getCruise(), log, sdt.getYear(), month, day, hour,
                                minute, acLat, acLon, intDist, f.getFreq(), f.getThreshold())
                        .map(o -> o == null ? "" : o.toString()).collect(Collectors.joining("\t")) + "\t";
            }).collect(Collectors.toList());
    String fil1 = path + "/" + fileName + ".txt";
    acList.add(0, Stream.of("Country", "Vessel", "Cruise", "Log", "Year", "Month", "Day", "Hour", "Min",
            "AcLat", "AcLon", "Logint", "Frequency", "Sv_threshold").collect(Collectors.joining("\t")));
    try {
        Files.write(Paths.get(fil1), acList, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException ex) {
        Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex);
    }
    acList.clear();
    // Acoustic values
    distances.stream().filter(d -> d.getPel_ch_thickness() != null)
            .flatMap(dist -> dist.getFrequencies().stream()).filter(fr -> freqFilterF.equals(fr.getFreq()))
            .forEachOrdered(f -> {
                try {
                    Double groupThicknessF = Math.max(f.getDistanceBO().getPel_ch_thickness(), groupThickness);
                    Map<String, Map<Integer, Double>> pivot = f.getSa().stream()
                            .filter(s -> s.getCh_type().equals("P")).map(s -> new SAGroup(s, groupThicknessF))
                            .filter(s -> s.getSpecies() != null
                                    && (specFilter == null || specFilter.equals(s.getSpecies())))
                            // create pivot table: species (dim1) -> depth interval index (dim2) -> sum sa (group aggregator)
                            .collect(Collectors.groupingBy(SAGroup::getSpecies, Collectors.groupingBy(
                                    SAGroup::getDepthGroupIdx, Collectors.summingDouble(SAGroup::sa))));
                    if (pivot.isEmpty() && specFilter != null && withZeros) {
                        pivot.put(specFilter, new HashMap<>());
                    }
                    Integer maxGroupIdx = pivot.entrySet().stream().flatMap(e -> e.getValue().keySet().stream())
                            .max(Integer::compare).orElse(null);
                    if (maxGroupIdx == null) {
                        return;
                    }
                    acList.addAll(pivot.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
                            .flatMap(e -> {
                                return IntStream.range(0, maxGroupIdx + 1).boxed().map(groupIdx -> {
                                    Double chUpDepth = groupIdx * groupThicknessF;
                                    Double chLowDepth = (groupIdx + 1) * groupThicknessF;
                                    Double sa = e.getValue().get(groupIdx);
                                    if (sa == null) {
                                        sa = 0d;
                                    }
                                    String res = null;
                                    if (withZeros || sa > 0d) {
                                        DistanceBO d = f.getDistanceBO();
                                        String log = Conversion.formatDoubletoDecimalString(d.getLog_start(),
                                                "0.0");
                                        LocalDateTime sdt = LocalDateTime
                                                .ofInstant(d.getStart_time().toInstant(), ZoneOffset.UTC);
                                        String month = StringUtils.leftPad(sdt.getMonthValue() + "", 2, "0");
                                        String day = StringUtils.leftPad(sdt.getDayOfMonth() + "", 2, "0");
                                        //String sas = String.format(Locale.UK, "%11.5f", sa);
                                        res = Stream
                                                .of(d.getNation(), d.getPlatform(), d.getCruise(), log,
                                                        sdt.getYear(), month, day, e.getKey(), chUpDepth,
                                                        chLowDepth, sa)
                                                .map(o -> o == null ? "" : o.toString())
                                                .collect(Collectors.joining("\t"));
                                    }
                                    return res;
                                }).filter(s -> s != null);
                            }).collect(Collectors.toList()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

    String fil2 = path + "/" + fileName + "Values.txt";
    acList.add(0, Stream.of("Country", "Vessel", "Cruise", "Log", "Year", "Month", "Day", "Species",
            "ChUppDepth", "ChLowDepth", "SA").collect(Collectors.joining("\t")));
    try {
        Files.write(Paths.get(fil2), acList, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException ex) {
        Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:hrytsenko.csv.IO.java

/**
 * Saves records into CSV file.//  w  w  w . ja v  a  2 s .  c  o  m
 * 
 * <p>
 * If file already exists, then it will be overridden.
 * 
 * @param args
 *            the named arguments {@link IO}.
 * 
 * @throws IOException
 *             if file could not be written.
 */
public static void save(Map<String, ?> args) throws IOException {
    Path path = getPath(args);
    LOGGER.info("Save: {}.", path.getFileName());

    @SuppressWarnings("unchecked")
    Collection<Record> records = (Collection<Record>) args.get("records");
    if (records.isEmpty()) {
        LOGGER.info("No records to save.");
        return;
    }

    try (Writer dataWriter = newBufferedWriter(path, getCharset(args), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING)) {
        Set<String> columns = new LinkedHashSet<>();
        List<Map<String, String>> rows = new ArrayList<>();
        for (Record record : records) {
            Map<String, String> values = record.values();
            columns.addAll(values.keySet());
            rows.add(values);
        }

        CsvSchema.Builder csvSchema = getSchema(args).setUseHeader(true);
        for (String column : columns) {
            csvSchema.addColumn(column);
        }
        CsvMapper csvMapper = new CsvMapper();
        ObjectWriter csvWriter = csvMapper.writer().withSchema(csvSchema.build());
        csvWriter.writeValue(dataWriter, rows);
    }
}

From source file:org.darkware.wpman.wpcli.WPCLI.java

/**
 * Update the local WP-CLI tool to the most recent version.
 *///from   w w w. j a v a 2 s. c  o  m
public static void update() {
    try {
        WPManager.log.info("Downloading new version of WP-CLI.");

        CloseableHttpClient httpclient = HttpClients.createDefault();

        URI pharURI = new URIBuilder().setScheme("http").setHost("raw.githubusercontent.com")
                .setPath("/wp-cli/builds/gh-pages/phar/wp-cli.phar").build();

        WPManager.log.info("Downloading from: {}", pharURI);
        HttpGet downloadRequest = new HttpGet(pharURI);

        CloseableHttpResponse response = httpclient.execute(downloadRequest);

        WPManager.log.info("Download response: {}", response.getStatusLine());
        WPManager.log.info("Download content type: {}", response.getFirstHeader("Content-Type").getValue());

        FileChannel wpcliFile = FileChannel.open(WPCLI.toolPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);

        response.getEntity().writeTo(Channels.newOutputStream(wpcliFile));
        wpcliFile.close();

        Set<PosixFilePermission> wpcliPerms = new HashSet<>();
        wpcliPerms.add(PosixFilePermission.OWNER_READ);
        wpcliPerms.add(PosixFilePermission.OWNER_WRITE);
        wpcliPerms.add(PosixFilePermission.OWNER_EXECUTE);
        wpcliPerms.add(PosixFilePermission.GROUP_READ);
        wpcliPerms.add(PosixFilePermission.GROUP_EXECUTE);

        Files.setPosixFilePermissions(WPCLI.toolPath, wpcliPerms);
    } catch (URISyntaxException e) {
        WPManager.log.error("Failure building URL for WPCLI download.", e);
        System.exit(1);
    } catch (IOException e) {
        WPManager.log.error("Error while downloading WPCLI client.", e);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:net.tuples.doitfx.connector.crypto.PasswordManager.java

private boolean generateNewPWStore(Path pStorePath) {

    final OutputStream storeOutStm;

    try {/*from w  w w  .j  av  a 2  s .com*/
        storeOutStm = Files.newOutputStream(pStorePath, StandardOpenOption.CREATE);

        pwStore = KeyStore.getInstance("JCEKS");

        pwStore.load(null, null);
        pwStore.store(storeOutStm, pwStorePassword.toCharArray());

        storeOutStm.close();

        return true;

    } catch (IOException ex) {
        Logger.getLogger(PasswordManager.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException ex) {
        Logger.getLogger(PasswordManager.class.getName()).log(Level.SEVERE, null, ex);
    }

    return false;
}

From source file:com.reactive.hzdfs.io.MemoryMappedChunkHandler.java

@Override
public void writeNext(FileChunk chunk) throws IOException {
    log.debug("[writeNext] " + chunk);
    if (file == null) {
        initWriteFile(chunk);//from w  w w. j a  v a  2 s .  com
        oStream = FileChannel.open(file.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE,
                StandardOpenOption.APPEND);

        /*
         * From javadocs:
         * "The behavior of this method when the requested region is not completely contained within this channel's file is unspecified. 
         * Whether changes made to the content or size of the underlying file, by this program or another, are propagated to the buffer 
         * is unspecified. The rate at which changes to the buffer are propagated to the file is unspecified."
         * 
         * Initially this is a 0 byte file. So how do we write to a new file??
         */
        log.debug("mapping byte buffer for write");
        mapBuff = oStream.map(MapMode.READ_WRITE, 0, chunk.getFileSize());

        if (log.isDebugEnabled()) {
            debugInitialParams();
            log.debug("Writing to target file- " + file + ". Expecting chunks to receive- " + chunk.getSize());
        }
    }

    doAttribCheck(chunk);

    //this is probably unreachable
    if (!mapBuff.hasRemaining()) {
        position += mapBuff.position();
        unmap(mapBuff);
        mapBuff = oStream.map(MapMode.READ_WRITE, position, chunk.getFileSize());
    }

    mapBuff.put(chunk.getChunk());
    fileSize += chunk.getChunk().length;

    if (fileSize > chunk.getFileSize())
        throw new IOException(
                "File size [" + fileSize + "] greater than expected size [" + chunk.getFileSize() + "]");

}