Example usage for java.nio.file StandardOpenOption TRUNCATE_EXISTING

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

Introduction

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

Prototype

StandardOpenOption TRUNCATE_EXISTING

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

Click Source Link

Document

If the file already exists and it is opened for #WRITE access, then its length is truncated to 0.

Usage

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  .java2s .c o  m*/
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

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();
    }/*w w w  .j ava2 s  .c  om*/

    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: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  2  s  .c o m*/
        System.err.println("No pid file. Did someone delete it while the program was running?");
    }
}

From source file:hrytsenko.csv.IO.java

/**
 * Saves records into CSV file.//from   w w w.  j a v a2s.  co  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   www . j  av a2s .  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:org.schedulesdirect.grabber.ProgramTask.java

@Override
public void run() {
    long start = System.currentTimeMillis();
    DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.PROGRAMS, clnt.getHash(),
            clnt.getUserAgent(), clnt.getBaseUrl());
    try {/*  ww  w  .j  a v a  2s . c o m*/
        JSONArray resp = Config.get().getObjectMapper().readValue(req.submitForJson(this.req), JSONArray.class);
        for (int i = 0; i < resp.length(); ++i) {
            JSONObject o = resp.getJSONObject(i);
            String id = o.optString("programID", "<unknown>");
            if (!JsonResponseUtils.isErrorResponse(o)) {
                if (id.startsWith("EP"))
                    seriesIds.add(Program.convertToSeriesId(id));
                Path p = vfs.getPath(targetDir, String.format("%s.txt", id));
                Files.write(p, o.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
            } else if (JsonResponseUtils.getErrorCode(o) == ApiResponse.INVALID_PROGID
                    || JsonResponseUtils.getErrorCode(o) == ApiResponse.PROGRAMID_QUEUED) {
                String msg = String.format("Missing program object: %s", id);
                if (!logMissingAtDebug)
                    LOG.warn(msg);
                else
                    LOG.debug(msg);
                if (retrySet != null)
                    retrySet.add(id);
            } else
                throw new InvalidJsonObjectException("Error received for Program", o.toString(3));
        }
    } catch (JSONException | JsonParseException e) {
        Grabber.failedTask = true;
        LOG.error("JSONError!", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        Grabber.failedTask = true;
        LOG.error("IOError receiving program data; filling in empty program info for non-existent program ids!",
                e);
        try {
            JSONArray ids = this.req;
            for (int i = 0; i < ids.length(); ++i) {
                String id = ids.getString(i);
                Path p = vfs.getPath(targetDir, String.format("%s.txt", id));
                if (!Files.exists(p))
                    Files.write(p, Program.EMPTY_PROGRAM.getBytes(ZipEpgClient.ZIP_CHARSET));
            }
        } catch (Exception x) {
            LOG.error("Unexpected error!", x);
            throw new RuntimeException(x);
        }
    }
    LOG.info(String.format("Completed ProgramTask in %dms [%d programs]", System.currentTimeMillis() - start,
            this.req.length()));
}

From source file:org.cryptomator.ui.settings.SettingsProvider.java

private void save(Settings settings) {
    Objects.requireNonNull(settings);
    try {/*from w  ww  .  j a  v  a2s .  com*/
        final Path settingsPath = getSettingsPath();
        Files.createDirectories(settingsPath.getParent());
        final OutputStream out = Files.newOutputStream(settingsPath, StandardOpenOption.WRITE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
        objectMapper.writeValue(out, settings);
        LOG.info("Settings saved to " + settingsPath);
    } catch (IOException e) {
        LOG.error("Failed to save settings.", e);
    }
}

From source file:com.fizzed.stork.deploy.Archive.java

static private void unpackEntry(ArchiveInputStream ais, Path target) throws IOException {
    // always make sure parent dir exists
    Files.createDirectories(target.getParent());

    try (OutputStream os = Files.newOutputStream(target, StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING)) {
        try (BufferedOutputStream bos = new BufferedOutputStream(os)) {
            int len = 0;
            byte[] BUFFER = new byte[1024];
            while ((len = ais.read(BUFFER)) != -1) {
                bos.write(BUFFER, 0, len);
            }/*from w ww .  j ava2s  .c  om*/
        }
    }
}

From source file:org.wikidata.wdtk.util.DirectoryManagerImpl.java

@Override
public long createFileAtomic(String fileName, InputStream inputStream) throws IOException {
    long fileSize;
    Path filePath = this.directory.resolve(fileName);
    Path fileTempPath = this.directory.resolve(fileName + ".part");

    try (ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
            FileChannel fc = FileChannel.open(fileTempPath, StandardOpenOption.WRITE,
                    StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE)) {
        fileSize = fc.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
    }/*from  w  w  w  .  j a v a2  s . c o  m*/

    Files.move(fileTempPath, filePath);

    return fileSize;
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.ContainerSecurityUpdaterTask.java

private void writeInternal(Path target, ByteBuffer data) throws IOException {
    try (FileChannel fc = FileChannel.open(target, StandardOpenOption.WRITE, StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING)) {
        int numOfRetries = 0;
        FileLock lock = null;//  www  .ja  v a 2 s  . c  o  m
        while (lock == null && numOfRetries < 5) {
            try {
                lock = fc.tryLock();
                fc.write(data);
            } catch (OverlappingFileLockException ex) {
                lock = null;
                numOfRetries++;
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException iex) {
                    throw new IOException(iex);
                }
            } finally {
                if (lock != null) {
                    lock.release();
                }
            }
        }
    }
}