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:processing.app.debug.Compiler.java

private void saveHex(String compiledSketch, String copyOfCompiledSketch, PreferencesMap dict)
        throws RunnerException {
    try {//from   w w  w  . j ava 2 s . c o m
        compiledSketch = StringReplacer.replaceFromMapping(compiledSketch, dict);
        copyOfCompiledSketch = StringReplacer.replaceFromMapping(copyOfCompiledSketch, dict);

        Path compiledSketchPath;
        Path compiledSketchPathInSubfolder = Paths.get(prefs.get("build.path"), "sketch", compiledSketch);
        Path compiledSketchPathInBuildPath = Paths.get(prefs.get("build.path"), compiledSketch);
        if (Files.exists(compiledSketchPathInSubfolder)) {
            compiledSketchPath = compiledSketchPathInSubfolder;
        } else {
            compiledSketchPath = compiledSketchPathInBuildPath;
        }

        Path copyOfCompiledSketchFilePath = Paths.get(this.sketch.getFolder().getAbsolutePath(),
                copyOfCompiledSketch);

        Files.copy(compiledSketchPath, copyOfCompiledSketchFilePath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new RunnerException(e);
    }
}

From source file:io.minio.MinioClient.java

/**
 * Gets object's data in the given bucket and stores it to given file name.
 *
 * </p><b>Example:</b><br>
 * <pre>{@code minioClient.getObject("my-bucketname", "my-objectname", "photo.jpg"); }</pre>
 *
 * @param bucketName  Bucket name./*w  w  w  . j  a  v  a2  s.  c  o  m*/
 * @param objectName  Object name in the bucket.
 * @param fileName    file name.
 *
 * @throws InvalidBucketNameException  upon invalid bucket name is given
 * @throws NoResponseException         upon no response from server
 * @throws IOException                 upon connection error
 * @throws XmlPullParserException      upon parsing response xml
 * @throws ErrorResponseException      upon unsuccessful execution
 * @throws InternalException           upon internal library error
 */
public void getObject(String bucketName, String objectName, String fileName)
        throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
        InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
        InternalException, InvalidArgumentException {
    Path filePath = Paths.get(fileName);
    boolean fileExists = Files.exists(filePath);

    if (fileExists && !Files.isRegularFile(filePath)) {
        throw new InvalidArgumentException(fileName + ": not a regular file");
    }

    ObjectStat objectStat = statObject(bucketName, objectName);
    long length = objectStat.length();
    String etag = objectStat.etag();

    String tempFileName = fileName + "." + etag + ".part.minio";
    Path tempFilePath = Paths.get(tempFileName);
    boolean tempFileExists = Files.exists(tempFilePath);

    if (tempFileExists && !Files.isRegularFile(tempFilePath)) {
        throw new IOException(tempFileName + ": not a regular file");
    }

    long tempFileSize = 0;
    if (tempFileExists) {
        tempFileSize = Files.size(tempFilePath);
        if (tempFileSize > length) {
            Files.delete(tempFilePath);
            tempFileExists = false;
            tempFileSize = 0;
        }
    }

    if (fileExists) {
        long fileSize = Files.size(filePath);
        if (fileSize == length) {
            // already downloaded. nothing to do
            return;
        } else if (fileSize > length) {
            throw new InvalidArgumentException(
                    "'" + fileName + "': object size " + length + " is smaller than file size " + fileSize);
        } else if (!tempFileExists) {
            // before resuming the download, copy filename to tempfilename
            Files.copy(filePath, tempFilePath);
            tempFileSize = fileSize;
            tempFileExists = true;
        }
    }

    InputStream is = null;
    OutputStream os = null;
    try {
        is = getObject(bucketName, objectName, tempFileSize);
        os = Files.newOutputStream(tempFilePath, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        long bytesWritten = ByteStreams.copy(is, os);
        is.close();
        os.close();

        if (bytesWritten != length - tempFileSize) {
            throw new IOException(tempFileName + ": unexpected data written.  expected = "
                    + (length - tempFileSize) + ", written = " + bytesWritten);
        }

        Files.move(tempFilePath, filePath, StandardCopyOption.REPLACE_EXISTING);
    } finally {
        if (is != null) {
            is.close();
        }
        if (os != null) {
            os.close();
        }
    }
}

From source file:Presentacion.FUsuarios.java

private void btnAddImagenesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAddImagenesMouseClicked

    try {// www .  j  a  v  a 2s.  com
        fc = new JFileChooser();
        fc.setAcceptAllFileFilterUsed(false); // No deja seleccionar todo tipo de archivos
        FileNameExtensionFilter filtroImagen = new FileNameExtensionFilter("Imgenes JPG, PNG & GIF", "jpg",
                "png", "gif");//Creo filtro para tipo de imagen
        fc.addChoosableFileFilter(filtroImagen);// Asigno el filtro creado de imagenes

        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {

            String path = this.getClass().getResource("Imagenes").getPath();

            File file = fc.getSelectedFile();
            userImgName = path + "\\" + txtRestNickname.getText() + "-" + urlsImages.size() + ".jpg";
            File fileToSave = new File(userImgName);
            FileWriter fileWr = new FileWriter(fileToSave);
            fileWr.close();
            Files.copy(fc.getSelectedFile().toPath(), fileToSave.toPath(), StandardCopyOption.REPLACE_EXISTING);
            urlsImages.add(txtRestNickname.getText() + "-" + urlsImages.size() + ".jpg");
        }

    } catch (HeadlessException | IOException ex) {
        JOptionPane.showMessageDialog(this, "Error al cargar imagen", "Error", JOptionPane.ERROR_MESSAGE);
        System.out.println("Error en alta cliente: " + ex.getMessage());
    }
}

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * Copy a File or a Directory inside the AUT workspace. Existing target
 * files / Directories are overwritten without warnings.
 *
 * @param relSourcePath//from ww w .j  av  a  2 s  .com
 *            the workspace relative path of the source file or directory to
 *            copy
 * @param relTargetPath
 *            the workspace relative path of the target file or directory
 */
public void copyInWorkspace(String relSourcePath, String relTargetPath) {

    LOGGER.info("kopiere. " + relSourcePath + " nach " + relTargetPath);

    File workspaceDir;
    try {
        workspaceDir = new File(getWorkspacePath());
    } catch (IOException e1) {
        String msg = "cannot find workspacePath";
        LOGGER.error(msg);
        throw new StopTestException(msg);
    }
    File source = new File(workspaceDir, relSourcePath);
    File target = new File(workspaceDir, relTargetPath);
    Path sourcePath = Paths.get(source.getAbsolutePath());
    Path targetPath = Paths.get(target.getAbsolutePath());

    if (!source.exists()) {
        String msg = "cannot copy '" + source + "': File does not exist";
        LOGGER.error(msg);
        throw new StopTestException(msg);
    }
    if (!source.canRead()) {
        String msg = "cannot copy '" + source + "': File cannot be read";
        LOGGER.error(msg);
        throw new StopTestException(msg);
    }

    if (source.isDirectory()) {
        try {
            copyFolder(sourcePath, targetPath);
        } catch (IOException e) {
            String msg = "cannot copy directory '" + source + "' to '" + target + "'";
            LOGGER.error(msg, e);
            throw new StopTestException(msg, e);
        }
    } else {
        try {
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            String msg = "cannot copy directory '" + source + "' to '" + target + "'";
            LOGGER.error(msg, e);
            throw new StopTestException(msg, e);
        }
    }

}

From source file:processing.app.debug.Compiler.java

private void copyAdditionalFilesToBuildFolderSavingOriginalFolderStructure(SketchData sketch, String buildPath)
        throws RunnerException {
    Path sketchPath = Paths.get(sketch.getFolder().getAbsolutePath());
    Stream<Path> otherFilesStream;
    try {//from ww  w  .j  a va  2s . c  om
        otherFilesStream = Files.find(sketchPath, ADDITIONAL_FILES_COPY_MAX_DEPTH,
                (path, attribs) -> !attribs.isDirectory() && isPathInASubfolder(sketchPath, path)
                        && FileUtils.hasExtension(path.toFile(), SketchData.OTHER_ALLOWED_EXTENSIONS));
    } catch (IOException e) {
        throw new RunnerException(e);
    }
    otherFilesStream
            .map((path) -> new Pair<>(path, Paths.get(buildPath, sketchPath.relativize(path).toString())))
            .forEach((pair) -> {
                try {
                    Files.createDirectories(pair.value.getParent());
                    Files.copy(pair.key, pair.value, StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(I18n.format(_("Problem moving {0} to the build folder"),
                            sketchPath.relativize(pair.key).toString()));
                }
            });
}

From source file:processing.app.debug.OldCompiler.java

private void copyAdditionalFilesToBuildFolderSavingOriginalFolderStructure(SketchData sketch, String buildPath)
        throws RunnerException {
    Path sketchPath = Paths.get(sketch.getFolder().getAbsolutePath());
    Stream<Path> otherFilesStream;
    try {/*from   w  w w  .  jav  a 2s  . c  om*/
        otherFilesStream = Files.find(sketchPath, ADDITIONAL_FILES_COPY_MAX_DEPTH,
                (path, attribs) -> !attribs.isDirectory() && isPathInASubfolder(sketchPath, path)
                        && FileUtils.hasExtension(path.toFile(), SketchData.OTHER_ALLOWED_EXTENSIONS));
    } catch (IOException e) {
        throw new RunnerException(e);
    }
    otherFilesStream
            .map((path) -> new Pair<>(path, Paths.get(buildPath, sketchPath.relativize(path).toString())))
            .forEach((pair) -> {
                try {
                    Files.createDirectories(pair.value.getParent());
                    Files.copy(pair.key, pair.value, StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(I18n.format(tr("Problem moving {0} to the build folder"),
                            sketchPath.relativize(pair.key).toString()));
                }
            });
}

From source file:org.roda.wui.api.controllers.BrowserHelper.java

public static void createOrUpdateAIPRepresentationPreservationMetadataFile(String aipId,
        String representationId, List<String> fileDirectoryPath, String fileId, InputStream is, boolean create)
        throws GenericException, RequestNotValidException, NotFoundException, AuthorizationDeniedException,
        ValidationException, AlreadyExistsException {
    Path file = null;/*w  w w.  j a  v a 2 s.  co  m*/
    try {
        ModelService model = RodaCoreFactory.getModelService();
        file = Files.createTempFile("preservation", ".tmp");
        Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
        ContentPayload payload = new FSPathContentPayload(file);
        boolean notify = true;
        if (create) {
            model.createPreservationMetadata(PreservationMetadataType.FILE, aipId, representationId,
                    fileDirectoryPath, fileId, payload, notify);
        } else {
            PreservationMetadataType type = PreservationMetadataType.FILE;
            String id = IdUtils.getPreservationFileId(fileId);
            model.updatePreservationMetadata(id, type, aipId, representationId, fileDirectoryPath, fileId,
                    payload, notify);
        }
    } catch (IOException e) {
        throw new GenericException("Error creating or updating AIP representation preservation metadata file",
                e);
    } finally {
        if (FSUtils.exists(file)) {
            try {
                Files.delete(file);
            } catch (IOException e) {
                LOGGER.warn("Error while deleting temporary file", e);
            }
        }
    }
}

From source file:org.dcm4chee.proxy.forward.ForwardFiles.java

private Collection<ForwardTask> scanFiles(ProxyAEExtension proxyAEE, String calledAET, File[] files) {
    HashMap<String, ForwardTask> map = new HashMap<String, ForwardTask>(4);
    for (File file : files) {
        try {// ww w .j  a v  a  2s.com
            if (lock.tryLock(100, TimeUnit.MILLISECONDS)) {
                try {
                    if (file.exists()) {
                        String prevFilePath = file.getPath();
                        File snd = new File(prevFilePath + ".snd");
                        try {
                            Files.move(file.toPath(), snd.toPath(), StandardCopyOption.REPLACE_EXISTING);
                            LOG.debug("Successfully renamed {} to {}", prevFilePath, snd.getPath());
                            LOG.debug("Adding file {} to forward tasks ", snd.getPath());
                            addFileToFwdTaskMap(proxyAEE, calledAET, snd, map);
                            LOG.debug(
                                    "Successfully added file {} to forward tasks , proceeding with scheduled send",
                                    snd.getPath());
                        } catch (Exception e) {
                            LOG.error(
                                    "Error moving {} to {}. Skip file for now and try again on next scheduler run. - {}",
                                    prevFilePath, snd.getPath(), e);
                            if (!file.exists() && snd.exists())
                                if (snd.renameTo(file))
                                    LOG.debug("Rename {} to {}", snd.getPath(), file.getPath());
                                else
                                    LOG.debug("Error renaming {} to {}", snd.getPath(), file.getPath());
                            else if (snd.exists() && file.exists())
                                try {
                                    Files.delete(snd.toPath());
                                } catch (Exception e1) {
                                    LOG.error(
                                            "Unable to delete file {} after failed rename from  {} to {}  - {}",
                                            snd, prevFilePath, snd.getPath(), e1);
                                }
                        }
                    }
                } finally {
                    lock.unlock();
                }
            }
        } catch (InterruptedException e) {
            LOG.error("Error acquiring lock for file scan and rename {}", e);
        }
    }
    return map.values();
}

From source file:eu.itesla_project.online.db.OnlineDbMVStore.java

@Override
public void exportStates(String workflowId, Path file) {
    if (workflowStatesFolderExists(workflowId)) {
        LOGGER.info("Exporting states for workflow {}", workflowId);
        Path workflowStatesFolder = getWorkflowStatesFolder(workflowId);
        Path csvFile = Paths.get(workflowStatesFolder.toString(), SERIALIZED_STATES_FILENAME);
        if (!csvFile.toFile().exists()) {
            LOGGER.info("Serializing network data of workflow {}", workflowId);
            try (FileWriter fileWriter = new FileWriter(csvFile.toFile());
                    CsvListWriter csvWriter = new CsvListWriter(fileWriter,
                            new CsvPreference.Builder('"', ';', "\r\n").build())) {
                boolean printHeaders = true;
                for (Integer stateId : listStoredStates(workflowId)) {
                    Network network = getState(workflowId, stateId);
                    if (network != null) {
                        Map<HistoDbAttributeId, Object> networkValues = IIDM2DB
                                .extractCimValues(network, new IIDM2DB.Config(network.getId(), true, true))
                                .getSingleValueMap();
                        if (printHeaders) {
                            List<String> headers = new ArrayList<>(networkValues.size());
                            for (HistoDbAttributeId attrId : networkValues.keySet()) {
                                headers.add(attrId.toString());
                            }//from  w  w  w . j a  v a  2s . c  o  m
                            ArrayList<String> headersList = new ArrayList<>();
                            headersList.add("workflow");
                            headersList.add("state");
                            headersList.addAll(Arrays.asList(headers.toArray(new String[] {})));
                            csvWriter.writeHeader(headersList.toArray(new String[] {}));
                            printHeaders = false;
                        }
                        ArrayList<Object> valuesList = new ArrayList<>();
                        valuesList.add(workflowId);
                        valuesList.add(stateId);
                        valuesList.addAll(Arrays.asList(networkValues.values().toArray()));
                        csvWriter.write(valuesList.toArray());
                    }
                }
            } catch (IOException e) {
                LOGGER.error("Error serializing network data for workflow {}", workflowId);
            }
        }
        try {
            Files.copy(csvFile, file, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else
        LOGGER.error("No stored states for workflow {}", workflowId);
}