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:dialog.DialogFunctionRoom.java

private void btnFunctionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFunctionActionPerformed
    String roomName = tfRoomName.getText();
    if (roomName.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Tn phng khng c  trng", "Error",
                JOptionPane.ERROR_MESSAGE);
        tfRoomName.requestFocus();/*from ww  w .j  a v a2 s  .  c  o m*/
        return;
    }
    String priceString = tfPrice.getText();
    if (priceString.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Gi phng khng c  trng", "Error",
                JOptionPane.ERROR_MESSAGE);
        tfPrice.requestFocus();
        return;
    }
    double price;
    try {
        price = Double.parseDouble(priceString);
    } catch (NumberFormatException nfe) {
        JOptionPane.showMessageDialog(null, "Gi phng khng ng nh dng", "Error",
                JOptionPane.ERROR_MESSAGE);
        return;
    }
    int max;
    try {
        max = Integer.parseInt(priceString);
    } catch (NumberFormatException nfe) {
        JOptionPane.showMessageDialog(null, "Gi phng khng ng nh dng", "Error",
                JOptionPane.ERROR_MESSAGE);
        return;
    }

    Floor objFloor = (Floor) cbFloor.getSelectedItem();
    int roomType = cbRoomType.getSelectedIndex() + 1;
    ModelPicture modelPicture = new ModelPicture();
    if (mType == Constant.TYPE_ADD) {
        if (mControllerRoom == null) {
            actionAddNoController();
            return;
        }
        String idRoom = UUID.randomUUID().toString();
        if (!mControllerRoom.isExistRoomInFloor(roomName, objFloor.getIdFloor())) {
            mListUriPhotos.stream().forEach((uriPicture) -> {
                File file = new File(uriPicture);
                String fileName = FilenameUtils.getBaseName(file.getName()) + "-" + System.nanoTime() + "."
                        + FilenameUtils.getExtension(file.getName());
                Path source = Paths.get(uriPicture);
                Path destination = Paths.get("files/" + fileName);
                try {
                    Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException ex) {
                    Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
                }
                Picture objPicture = new Picture(UUID.randomUUID().toString(), idRoom, fileName);
                modelPicture.addItem(objPicture);
                mListPictures.add(objPicture);
            });
            Room objRoom = new Room(idRoom, objFloor.getIdFloor(), roomName, roomType, price,
                    Constant.ROOM_CONDITION_AVAILABLE_TYPE, mListPictures, null, objFloor.getFloorName(), max);
            mObjRoom = objRoom;
            if (mControllerRoom.addItem(objRoom)) {
                objFloor.setMaxRoom(objFloor.getMaxRoom() + 1);
                new ModelFloor().editItem(objFloor);
                ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png").getPath());
                JOptionPane.showMessageDialog(this, "Thm thnh cng!", "Success",
                        JOptionPane.INFORMATION_MESSAGE, icon);
                this.dispose();
            }
        } else {
            JOptionPane.showMessageDialog(this, "Phng  tn ti!", "Error", JOptionPane.ERROR_MESSAGE);
        }
    } else if (mType == Constant.TYPE_EDIT) {
        mObjRoom.setFloorName(objFloor.getFloorName());
        mObjRoom.setRoomName(roomName);
        mObjRoom.setPrice(price);
        mObjRoom.setIdFloor(objFloor.getIdFloor());
        mObjRoom.setMax(max);
        mObjRoom.setType(cbRoomType.getSelectedIndex() + 1);
        mListUriPhotos.stream().forEach((uriPicture) -> {
            File file = new File(uriPicture);
            String fileName = FilenameUtils.getBaseName(file.getName()) + "-" + System.nanoTime() + "."
                    + FilenameUtils.getExtension(file.getName());
            Path source = Paths.get(uriPicture);
            Path destination = Paths.get("files/" + fileName);
            try {
                Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException ex) {
                Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
            }
            Picture objPicture = new Picture(UUID.randomUUID().toString(), mObjRoom.getIdRoom(), fileName);
            modelPicture.addItem(objPicture);
            mListPictures.add(objPicture);
        });
        mObjRoom.setListPicture(mListPictures);
        if (mControllerRoom.editItem(mObjRoom, mRow)) {
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png").getPath());
            JOptionPane.showMessageDialog(this, "Sa thnh cng!", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
            this.dispose();
        }
    }
}

From source file:org.perfcake.util.Utils.java

/**
 * Atomically writes given content to a file.
 *
 * @param path//from www  .  j a  v  a 2  s  .  co  m
 *       The target file path.
 * @param content
 *       The content to be written.
 * @throws org.perfcake.PerfCakeException
 *       In the case of file operations failure.
 */
public static void writeFileContent(final Path path, final String content) throws PerfCakeException {
    try {
        final Path workFile = Paths.get(path.toString() + ".work");
        Files.write(workFile, content.getBytes(Utils.getDefaultEncoding()));
        Files.move(workFile, path, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
    } catch (final IOException e) {
        final String message = String.format("Could not write content to the file %s:", path.toString());
        throw new PerfCakeException(message, e);
    }
}

From source file:fr.inria.soctrace.tools.ocelotl.core.caches.DataCache.java

/**
 * Save the cache of the current trace to the specified path
 * //from www. j ava2s .  com
 * @param oParam
 *            current parameters
 * @param destPath
 *            path to save the file
 */
public void saveDataCacheTo(OcelotlParameters oParam, String destPath) {
    // Get the current cache file
    CacheParameters params = new CacheParameters(oParam);
    File source = null;

    // Look for the corresponding file
    for (CacheParameters par : cachedData.keySet()) {
        if (similarParameters(params, par)) {
            source = cachedData.get(par);
        }
    }

    if (source != null) {
        File dest = new File(destPath);

        try {
            Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        logger.error("No corresponding cache file was found");
    }
}

From source file:de.cebitec.readXplorer.differentialExpression.plot.BaySeqGraphicsTopComponent.java

private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
    ReadXplorerFileChooser fc = new ReadXplorerFileChooser(new String[] { "svg" }, "svg") {
        private static final long serialVersionUID = 1L;

        @Override/*  w w w.  j av  a 2  s  .c o m*/
        public void save(String fileLocation) {
            Path to = FileSystems.getDefault().getPath(fileLocation, "");
            BaySeqAnalysisHandler.Plot selectedPlot = (BaySeqAnalysisHandler.Plot) plotTypeComboBox
                    .getSelectedItem();
            if (selectedPlot == BaySeqAnalysisHandler.Plot.MACD) {
                saveToSVG(fileLocation);
            } else {
                Path from = currentlyDisplayed.toPath();
                try {
                    Path outputFile = Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
                    messages.setText("SVG image saved to " + outputFile.toString());
                } catch (IOException ex) {
                    Date currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "{0}: " + ex.getMessage(),
                            currentTimestamp);
                    JOptionPane.showMessageDialog(null, ex.getMessage(), "Could not write to file.",
                            JOptionPane.WARNING_MESSAGE);
                }
            }
        }

        @Override
        public void open(String fileLocation) {
        }
    };
    fc.openFileChooser(ReadXplorerFileChooser.SAVE_DIALOG);
}

From source file:org.eclipse.cdt.arduino.core.internal.board.ArduinoManager.java

public Collection<ArduinoLibrary> getLibraryUpdates(IProgressMonitor monitor) throws CoreException {
    try {//from w  ww .  j av a  2s.  c o m
        initInstalledLibraries();
        Map<String, ArduinoLibrary> libs = new HashMap<>();

        SubMonitor sub = SubMonitor.convert(monitor, "Downloading library index", 2);
        Path librariesPath = ArduinoPreferences.getArduinoHome().resolve(LIBRARIES_FILE);
        URL librariesUrl = new URL(LIBRARIES_URL);
        Files.createDirectories(ArduinoPreferences.getArduinoHome());
        Files.copy(librariesUrl.openStream(), librariesPath, StandardCopyOption.REPLACE_EXISTING);
        sub.worked(1);

        try (Reader reader = new FileReader(librariesPath.toFile())) {
            sub.setTaskName("Calculating library updates");
            LibraryIndex libraryIndex = new Gson().fromJson(reader, LibraryIndex.class);
            for (ArduinoLibrary library : libraryIndex.getLibraries()) {
                String libraryName = library.getName();
                ArduinoLibrary installed = installedLibraries.get(libraryName);
                if (installed != null && compareVersions(library.getVersion(), installed.getVersion()) > 0) {
                    ArduinoLibrary current = libs.get(libraryName);
                    if (current == null || compareVersions(library.getVersion(), current.getVersion()) > 0) {
                        libs.put(libraryName, library);
                    }
                }
            }
        }
        sub.done();
        return libs.values();
    } catch (IOException e) {
        throw Activator.coreException(e);
    }
}

From source file:org.matonto.etl.rest.impl.DelimitedRestImplTest.java

private void copyResourceToTemp(String resourceName, String newName) throws IOException {
    Files.copy(getClass().getResourceAsStream("/" + resourceName),
            Paths.get(DelimitedRestImpl.TEMP_DIR + "/" + newName), StandardCopyOption.REPLACE_EXISTING);
}

From source file:com.bekwam.mavenpomupdater.MainViewController.java

public void doUpdate() {

    for (POMObject p : tblPOMS.getItems()) {

        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] p=" + p.getAbsPath());
        }//from   w  ww.j a  v a  2  s  . c o m

        if (p.getParseError()) {
            if (log.isDebugEnabled()) {
                log.debug("[DO UPDATE] skipping update of p=" + p.getAbsPath()
                        + " because of a parse error on scanning");
            }
            continue;
        }

        if (!p.getUpdate()) {
            if (log.isDebugEnabled()) {
                log.debug("[DO UPDATE] skipping update of p=" + p.getAbsPath()
                        + " because user excluded it from update");
            }
            continue;
        }

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(false);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(p.getAbsPath());

            if (p.getParentVersion() != null && p.getParentVersion().length() > 0) {
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression expression = xpath.compile("//project/parent/version/text()");
                Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);

                if (StringUtils.isNotEmpty(tfNewVersion.getText())) {
                    node.setNodeValue(tfNewVersion.getText());
                } else { // editing individual table cells
                    node.setNodeValue(p.getParentVersion());
                }
            }

            if (p.getVersion() != null && p.getVersion().length() > 0) {
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression expression = xpath.compile("//project/version/text()");
                Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);

                if (StringUtils.isNotEmpty(tfNewVersion.getText())) {
                    node.setNodeValue(tfNewVersion.getText());
                } else { // editing individual table cells
                    node.setNodeValue(p.getVersion());
                }
            }

            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();

            String workingFileName = p.getAbsPath() + ".mpu";
            FileWriter fw = new FileWriter(workingFileName);
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(fw);
            transformer.transform(source, result);
            fw.close();

            Path src = FileSystems.getDefault().getPath(workingFileName);
            Path target = FileSystems.getDefault().getPath(p.getAbsPath());

            Files.copy(src, target, StandardCopyOption.REPLACE_EXISTING);

            Files.delete(src);

        } catch (Exception exc) {
            log.error("error updating poms", exc);
        }
    }

    if (StringUtils.isNotEmpty(tfRootDir.getText())) {
        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] issuing rescan command");
        }
        scan();
    } else {
        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] did an update, but there is not value in root; clearing");
        }
        tblPOMS.getItems().clear();
    }
    tblPOMSDirty = false;
    tfNewVersion.setDisable(false);
}

From source file:info.novatec.inspectit.rcp.storage.util.DataRetriever.java

/**
 * Downloads and saves locally wanted files associated with given {@link StorageData}. Files
 * will be saved in passed directory. The caller can specify the type of the files to download
 * by passing the proper {@link StorageFileType}s to the method.
 * // w w w.  j  a v  a  2s  .c om
 * @param cmrRepositoryDefinition
 *            {@link CmrRepositoryDefinition}.
 * @param storageData
 *            {@link StorageData}.
 * @param directory
 *            Directory to save objects. compressBefore Should data files be compressed on the
 *            fly before sent.
 * @param compressBefore
 *            Should data files be compressed on the fly before sent.
 * @param decompressContent
 *            If the useGzipCompression is <code>true</code>, this parameter will define if the
 *            received content will be de-compressed. If false is passed content will be saved
 *            to file in the same format as received, but the path of the file will be altered
 *            with additional '.gzip' extension at the end.
 * @param subMonitor
 *            {@link SubMonitor} for process reporting.
 * @param fileTypes
 *            Files that should be downloaded.
 * @throws BusinessException
 *             If directory to save does not exists. If files wanted can not be found on the
 *             server.
 * @throws IOException
 *             If {@link IOException} occurs.
 */
public void downloadAndSaveStorageFiles(CmrRepositoryDefinition cmrRepositoryDefinition,
        StorageData storageData, final Path directory, boolean compressBefore, boolean decompressContent,
        SubMonitor subMonitor, StorageFileType... fileTypes) throws BusinessException, IOException {
    if (!Files.isDirectory(directory)) {
        throw new BusinessException("Download and save storage files for storage " + storageData
                + " to the path " + directory.toString() + ".", StorageErrorCodeEnum.FILE_DOES_NOT_EXIST);
    }

    Map<String, Long> allFiles = getFilesFromCmr(cmrRepositoryDefinition, storageData, fileTypes);

    if (MapUtils.isNotEmpty(allFiles)) {
        PostDownloadRunnable postDownloadRunnable = new PostDownloadRunnable() {
            @Override
            public void process(InputStream content, String fileName) throws IOException {
                String[] splittedFileName = fileName.split("/");
                Path writePath = directory;
                // first part is empty, second is storage id, we don't need it
                for (int i = 2; i < splittedFileName.length; i++) {
                    writePath = writePath.resolve(splittedFileName[i]);
                }
                // ensure all dirs are created
                if (Files.notExists(writePath.getParent())) {
                    Files.createDirectories(writePath.getParent());
                }
                Files.copy(content, writePath, StandardCopyOption.REPLACE_EXISTING);
            }
        };
        this.downloadAndSaveObjects(cmrRepositoryDefinition, allFiles, postDownloadRunnable, compressBefore,
                decompressContent, subMonitor);
    }
}

From source file:org.ligoj.app.plugin.prov.aws.ProvAwsTerraformService.java

private void copy(final Context context, final String... fragments) throws IOException {
    Files.copy(toInput(String.join("/", fragments)),
            utils.toFile(context.getSubscription(), fragments).toPath(), StandardCopyOption.REPLACE_EXISTING);
}

From source file:com.cloudbees.clickstack.util.Files2.java

/**
 * Copy content for {@code srcDir} to {@code destDir}
 *
 * @param srcDir//  w w  w .j  a  v a 2 s  . c o m
 * @param destDir
 * @throws RuntimeIOException
 */
public static void copyDirectoryContent(@Nonnull final Path srcDir, @Nonnull final Path destDir)
        throws RuntimeIOException {
    logger.trace("Copy from {} to {}", srcDir, destDir);

    FileVisitor<Path> copyDirVisitor = new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            Path targetPath = destDir.resolve(srcDir.relativize(dir));
            if (!Files.exists(targetPath)) {
                Files.createDirectory(targetPath);
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.copy(file, destDir.resolve(srcDir.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
            return FileVisitResult.CONTINUE;
        }
    };
    try {
        Files.walkFileTree(srcDir, copyDirVisitor);
    } catch (IOException e) {
        throw new RuntimeIOException("Exception copying content of dir " + srcDir + " to " + destDir, e);
    }
}