Example usage for java.nio.file StandardCopyOption REPLACE_EXISTING

List of usage examples for java.nio.file StandardCopyOption REPLACE_EXISTING

Introduction

In this page you can find the example usage for java.nio.file StandardCopyOption REPLACE_EXISTING.

Prototype

StandardCopyOption REPLACE_EXISTING

To view the source code for java.nio.file StandardCopyOption REPLACE_EXISTING.

Click Source Link

Document

Replace an existing file if it exists.

Usage

From source file:de._692b8c32.cdlauncher.tasks.GoogleDownloadTask.java

@Override
public void doWork() {
    setProgress(-1);/*ww w  . j ava 2 s.  c  om*/

    try {
        HttpClient client = HttpClients.createDefault();
        String realUrl = null;
        Pattern pattern = Pattern.compile(
                "<a id=\"uc-download-link\" class=\"goog-inline-block jfk-button jfk-button-action\" href=\"([^\"]*)\">");
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(client.execute(new HttpGet(fileUrl)).getEntity().getContent()))) {
            for (String line : reader.lines().collect(Collectors.toList())) {
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    realUrl = fileUrl.substring(0, fileUrl.lastIndexOf('/'))
                            + matcher.group(1).replace("&amp;", "&");
                    break;
                }
            }
        }

        if (realUrl == null) {
            throw new RuntimeException("Failed to find real url");
        } else {
            try (InputStream stream = client.execute(new HttpGet(realUrl)).getEntity().getContent()) {
                Files.copy(stream, cacheFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
        }
    } catch (IOException ex) {
        throw new RuntimeException("Could not download data", ex);
    }
}

From source file:org.metaservice.frontend.rest.cache.FileSystemCacheResourceService.java

private InputStream cacheResource(InputStream inputStream, String resource, String mimetype)
        throws IOException {
    byte[] content = org.apache.commons.io.IOUtils.toByteArray(inputStream);

    Path source = Files.createTempFile(DigestUtils.md5Hex(resource), getExtension(mimetype));
    try (OutputStream outputStream = new FileOutputStream(source.toFile())) {
        IOUtils.write(content, outputStream);
    }/*from   w ww.ja  va2  s. com*/

    Path target = getCacheFile(resource, mimetype).toPath();
    if (!target.getParent().toFile().isDirectory()) {
        Files.createDirectories(target.getParent());
    }
    Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    return new ByteArrayInputStream(content);
}

From source file:io.github.zlika.reproducible.ZipStripper.java

@Override
public void strip(File in, File out) throws IOException {
    try (final ZipFile zip = new ZipFile(in);
            final ZipArchiveOutputStream zout = new ZipArchiveOutputStream(out)) {
        final List<String> sortedNames = sortEntriesByName(zip.getEntries());
        for (String name : sortedNames) {
            final ZipArchiveEntry entry = zip.getEntry(name);
            // Strip Zip entry
            final ZipArchiveEntry strippedEntry = filterZipEntry(entry);
            // Strip file if required
            final Stripper stripper = getSubFilter(name);
            if (stripper != null) {
                // Unzip entry to temp file
                final File tmp = File.createTempFile("tmp", null);
                tmp.deleteOnExit();//ww  w.  j  a v  a  2s. c om
                Files.copy(zip.getInputStream(entry), tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
                final File tmp2 = File.createTempFile("tmp", null);
                tmp2.deleteOnExit();
                stripper.strip(tmp, tmp2);
                final byte[] fileContent = Files.readAllBytes(tmp2.toPath());
                strippedEntry.setSize(fileContent.length);
                zout.putArchiveEntry(strippedEntry);
                zout.write(fileContent);
                zout.closeArchiveEntry();
            } else {
                // Copy the Zip entry as-is
                zout.addRawArchiveEntry(strippedEntry, getRawInputStream(zip, entry));
            }
        }
    }
}

From source file:org.thingsboard.server.service.install.cql.CassandraDbHelper.java

public static void appendToEndOfLine(Path targetDumpFile, String toAppend) throws Exception {
    Path tmp = Files.createTempFile(null, null);
    try (CSVParser csvParser = new CSVParser(Files.newBufferedReader(targetDumpFile), CSV_DUMP_FORMAT)) {
        try (CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(tmp), CSV_DUMP_FORMAT)) {
            csvParser.forEach(record -> {
                List<String> newRecord = new ArrayList<>();
                record.forEach(val -> newRecord.add(val));
                newRecord.add(toAppend);
                try {
                    csvPrinter.printRecord(newRecord);
                } catch (IOException e) {
                    throw new RuntimeException("Error appending to EOL", e);
                }/*from www.  jav  a  2s  . c om*/
            });
        }
    }
    Files.move(tmp, targetDumpFile, StandardCopyOption.REPLACE_EXISTING);
}

From source file:org.forgerock.openidm.maintenance.upgrade.FileStateCheckerTest.java

@Test
public void testUpdateStateWithChange() throws IOException, URISyntaxException, NoSuchAlgorithmException {
    Files.copy(Paths.get(getClass().getResource("/checksums2.csv").toURI()), tempFile,
            StandardCopyOption.REPLACE_EXISTING);
    ChecksumFile tempChecksumFile = new ChecksumFile(tempFile);
    FileStateChecker checker = new FileStateChecker(tempChecksumFile);
    Path filepath = Paths.get("file1");
    checker.updateState(filepath);//w ww.  ja  v a2  s . co  m
    checker = new FileStateChecker(tempChecksumFile);
    assertThat(checker.getCurrentFileState(filepath).equals(FileState.DIFFERS));
}

From source file:controladores.subirArchivo.java

public void guardarPrime() {
    try {//from   w  w w .ja va2s . c o  m
        //guardar los datos
        //???????????
        //guardando los requisitos
        for (UploadedFile f : files) {
            if (f != null) {
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date dateobj = new Date();

                String nombreFecha = ("chiting" + "-" + df.format(dateobj).replaceAll(":", "-")).trim();
                File directorio = new File("d:/Postgrado/inscripciones/requisitos/" + nombreFecha);
                if (!directorio.exists()) {
                    directorio.mkdir();
                }

                String filename = f.getFileName();
                // String extension = f.getContentType();
                Path ruta = Paths.get(directorio + filename);

                try (InputStream input = f.getInputstream()) {
                    Files.copy(input, ruta, StandardCopyOption.REPLACE_EXISTING);
                }
                FacesMessage message = new FacesMessage("Succesful", filename + " is uploaded.");
                FacesContext.getCurrentInstance().addMessage(null, message);
            }
        }

    } catch (Exception ex) {
        Logger.getLogger(subirArchivo.class.getName()).log(Level.SEVERE, null, ex);
        FacesMessage message = new FacesMessage("Succesful", ex.toString());
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

}

From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceFileHandler.java

/**
 * @see WorkspaceFileHandler#copyFile(java.io.File, java.io.File)
 */// ww w .  jav a 2s  .  c  om
@Override
public void copyFile(File originNodeFile, File targetNodeFile) throws IOException {

    Files.copy(originNodeFile.toPath(), targetNodeFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

From source file:org.sejda.sambox.pdmodel.graphics.image.JPEGFactoryTest.java

@Test
public void testCreateFromFile256() throws IOException {
    try (InputStream stream = JPEGFactoryTest.class.getResourceAsStream("jpeg256.jpg")) {
        File file = folder.newFile();
        Files.copy(stream, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        PDImageXObject ximage = JPEGFactory.createFromFile(file);
        validate(ximage, 8, 344, 287, "jpg", PDDeviceGray.INSTANCE.getName());

        doWritePDF(new PDDocument(), ximage, testResultsDir, "jpeg256stream.pdf");
        checkJpegStream(testResultsDir, "jpeg256stream.pdf",
                JPEGFactoryTest.class.getResourceAsStream("jpeg256.jpg"));
    }/*from   w w  w .j av  a2 s  .  c  o  m*/
}

From source file:dk.ekot.misc.SynchronizedCache.java

protected void copy(Path fullSourcePath, Path fullCachePath) throws IOException {
    Files.createDirectories(fullCachePath.getParent());
    Files.copy(fullSourcePath, fullCachePath, StandardCopyOption.REPLACE_EXISTING);
}

From source file:org.schedulesdirect.grabber.LogoTask.java

@Override
public void run() {
    if (req != null && url != null) {
        long start = System.currentTimeMillis();
        try {// www  . j a  v a  2s.  c o m
            HttpResponse resp = Request.Get(url.toURI()).execute().returnResponse();
            StatusLine status = resp.getStatusLine();
            if (status.getStatusCode() == 200) {
                try (InputStream ins = resp.getEntity().getContent()) {
                    Path p = vfs.getPath("logos", String.format("%s.%s", callsign, ext));
                    Files.copy(ins, p, StandardCopyOption.REPLACE_EXISTING);
                    if (md5 != null)
                        synchronized (cache) {
                            cache.put(callsign, md5);
                        }
                    if (LOG.isTraceEnabled())
                        LOG.trace(String.format("LogoTask COMPLETE for %s [%dms]", callsign,
                                System.currentTimeMillis() - start));
                }
            } else {
                LOG.warn(String.format("Received error response for logo '%s': %s", callsign,
                        resp.getStatusLine()));
                if (status.getStatusCode() >= 400 && status.getStatusCode() <= 499)
                    removeStaleLogo();
            }
        } catch (IOException | URISyntaxException e) {
            LOG.error(String.format("IOError grabbing logo for %s", callsign), e);
        }
    } else if (LOG.isTraceEnabled())
        LOG.trace(String.format("No logo info for %s", callsign));
}