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:org.caleydo.data.importer.tcga.FirehoseProvider.java

private static File parseMAF(File maf) {

    File out = new File(maf.getParentFile(), "P" + maf.getName());
    if (out.exists())
        return out;
    log.fine(maf.getAbsolutePath() + " parsing maf file");
    final String TAB = "\t";

    try (BufferedReader reader = Files.newBufferedReader(maf.toPath(), Charset.forName("UTF-8"))) {
        List<String> header = Arrays.asList(reader.readLine().split(TAB));
        int geneIndex = header.indexOf("Hugo_Symbol");
        int sampleIndex = header.indexOf("Tumor_Sample_Barcode");
        // gene x sample x mutated
        Table<String, String, Boolean> mutated = TreeBasedTable.create();
        String line = null;/*w  ww  . ja va  2s . c o m*/
        while ((line = reader.readLine()) != null) {
            String[] columns = line.split(TAB);
            mutated.put(columns[geneIndex], columns[sampleIndex], Boolean.TRUE);
        }

        File tmp = new File(out.getParentFile(), out.getName() + ".tmp");
        PrintWriter w = new PrintWriter(tmp);
        w.append("Hugo_Symbol");
        List<String> cols = new ArrayList<>(mutated.columnKeySet());
        for (String sample : cols) {
            w.append(TAB).append(sample);
        }
        w.println();
        Set<String> rows = mutated.rowKeySet();
        for (String gene : rows) {
            w.append(gene);
            for (String sample : cols) {
                w.append(TAB).append(mutated.contains(gene, sample) ? '1' : '0');
            }
            w.println();
        }
        w.close();
        Files.move(tmp.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING);

        log.fine(maf.getAbsolutePath() + " parsed maf file stats: " + mutated.size() + " " + rows.size() + " "
                + cols.size());
        return out;
    } catch (IOException e) {
        log.log(Level.SEVERE, maf.getAbsolutePath() + " maf parsing error: " + e.getMessage(), e);
    }
    return null;
}

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

public Collection<ArduinoLibrary> getAvailableLibraries(IProgressMonitor monitor) throws CoreException {
    try {/*w  ww .  j  a  v  a  2s . co  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 available libraries");
            LibraryIndex libraryIndex = new Gson().fromJson(reader, LibraryIndex.class);
            for (ArduinoLibrary library : libraryIndex.getLibraries()) {
                String libraryName = library.getName();
                if (!installedLibraries.containsKey(libraryName)) {
                    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:com.collaborne.jsonschema.generator.pojo.PojoGenerator.java

@VisibleForTesting
protected void writeSource(URI type, ClassName className, Buffer buffer) throws IOException {
    // Create the file based on the className in the mapping
    Path outputFile = getClassSourceFile(className);
    logger.info("{}: Writing {}", type, outputFile);

    // Write stuff into it
    Files.createDirectories(outputFile.getParent());
    Files.copy(buffer.getInputStream(), outputFile, StandardCopyOption.REPLACE_EXISTING);
}

From source file:nextflow.fs.dx.DxFileSystemProvider.java

/**
 * Implements the *copy* operation using the DnaNexus API *clone*
 *
 *
 * <p>//  w w w.j  ava2 s .c  o m
 * See clone https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2Fclone
 *
 * @param source
 * @param target
 * @param options
 * @throws IOException
 */

@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {

    List<CopyOption> opts = Arrays.asList(options);
    boolean targetExists = Files.exists(target);

    if (targetExists) {
        if (Files.isRegularFile(target)) {
            if (opts.contains(StandardCopyOption.REPLACE_EXISTING)) {
                Files.delete(target);
            } else {
                throw new FileAlreadyExistsException("Copy failed -- target file already exists: " + target);
            }

        } else if (Files.isDirectory(target)) {
            target = target.resolve(source.getFileName());
        } else {
            throw new UnsupportedOperationException();
        }
    }

    String name1 = source.getFileName().toString();
    String name2 = target.getFileName().toString();
    if (!name1.equals(name2)) {
        throw new UnsupportedOperationException(
                "Copy to a file with a different name is not supported: " + source.toString());
    }

    final DxPath dxSource = toDxPath(source);
    final DxFileSystem dxFileSystem = dxSource.getFileSystem();
    dxFileSystem.fileCopy(dxSource, toDxPath(target));
}

From source file:org.apache.nifi.processors.standard.FetchFile.java

protected void move(final File source, final File target, final boolean overwrite) throws IOException {
    final File targetDirectory = target.getParentFile();

    // convert to path and use Files.move instead of file.renameTo so that if we fail, we know why
    final Path targetPath = target.toPath();
    if (!targetDirectory.exists()) {
        Files.createDirectories(targetDirectory.toPath());
    }/*w w w . j  a v  a  2  s .  com*/

    final CopyOption[] copyOptions = overwrite ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING }
            : new CopyOption[] {};
    Files.move(source.toPath(), targetPath, copyOptions);
}

From source file:org.dcm4che3.tool.wadouri.WadoURI.java

private static String writeFile(InputStream in, WadoURI main, String extension) {
    File file = new File(main.getOutDir(), main.getOutFileName() + extension);
    try {/*  w  w w  .  j  av a  2  s .c o  m*/
        Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        System.out.println("wadouri: Error writing results to file " + e.getMessage());
    }
    return file.getAbsolutePath();
}

From source file:fr.moribus.imageonmap.migration.V3Migrator.java

/**
 * Makes a standard file copy, and checks the integrity of the destination 
 * file after the copy//  www.j  a v a 2 s .c  o  m
 * @param sourceFile The file to copy
 * @param destinationFile The destination file
 * @throws IOException If the copy failed, if the integrity check failed, or if the destination file already exists
 */
static private void verifiedBackupCopy(File sourceFile, File destinationFile) throws IOException {
    if (destinationFile.exists())
        throw new IOException(
                "Backup copy failed : destination file (" + destinationFile.getName() + ") already exists.");

    long sourceSize = sourceFile.length();
    String sourceCheckSum = fileCheckSum(sourceFile, "SHA1");

    Path sourcePath = Paths.get(sourceFile.getAbsolutePath());
    Path destinationPath = Paths.get(destinationFile.getAbsolutePath());
    Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);

    long destinationSize = destinationFile.length();
    String destinationCheckSum = fileCheckSum(destinationFile, "SHA1");

    if (sourceSize != destinationSize || !sourceCheckSum.equals(destinationCheckSum)) {
        throw new IOException("Backup copy failed : source and destination files (" + sourceFile.getName()
                + ") differ after copy.");
    }

}

From source file:com.xse.optstack.persconftool.base.persistence.PersConfExport.java

private static void copyDefaultDataFiles(final File targetBaseFolder, final EApplication application,
        final Function<EConfiguration, EDefaultData> defaultDataProvider) {
    for (final EResource eResource : application.getResources()) {
        // copy default data files in case we have a file-based default data configuration with new file refs
        if (eResource.getConfiguration().getType() == EDefaultDataType.FILE) {
            final EDefaultData factoryDefaultData = defaultDataProvider.apply(eResource.getConfiguration());
            if (!StringUtils.isEmpty(factoryDefaultData.getLocalResourcePath())) {
                final File dataFile = new File(factoryDefaultData.getLocalResourcePath());
                if (dataFile.exists() && dataFile.canRead()) {
                    try {
                        final Path source = Paths.get(dataFile.toURI());
                        final Path target = Paths.get(new File(
                                targetBaseFolder.getAbsolutePath() + File.separator + eResource.getName())
                                        .toURI());
                        Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
                    } catch (final IOException | IllegalArgumentException | SecurityException e) {
                        Logger.error(Activator.PLUGIN_ID,
                                "Error copying factory default file to target location: " + eResource.getName(),
                                e);/*from w ww  . j a v a2 s .c  o m*/
                    }
                } else {
                    Logger.warn(Activator.PLUGIN_ID, "Invalid factory default data path!");
                }
            }
        }
    }
}

From source file:org.sigmah.server.servlet.FileServlet.java

/**
 * Processes the file upload./*  ww  w .  j a  va2s.c o m*/
 * 
 * @param request
 *          The HTTP request.
 * @param response
 *          The HTTP response.
 * @param context
 *          The execution context.
 * @param filename
 *          The uploaded physical file name.
 * @param logo
 *          {@code true} if the upload concerns an organization logo, {@code false} otherwise.
 * @throws java.io.IOException
 *           If an error occured while reading or writing to the socket or if an error occured while storing the
 *           uploaded file.
 * @throws org.sigmah.server.servlet.base.StatusServletException
 *           if the request type is not MULTIPART or if the file exceeded the maximum allowed size.
 * @throws org.apache.commons.fileupload.FileUploadException
 *           If an error occured while reading the uploaded file.
 */
private long processUpload(final MultipartRequest multipartRequest, final HttpServletResponse response,
        final String filename, final boolean logo)
        throws StatusServletException, IOException, FileUploadException {
    LOG.debug("Starting file uploading...");

    final long[] size = { 0L };
    multipartRequest.parse(new MultipartRequestCallback() {

        @Override
        public void onInputStream(InputStream inputStream, String itemName, String mimeType)
                throws IOException {
            // Retrieving file name.
            // If a name (id) is provided, we use it. If not, using the name of the uploaded file.
            final String name = StringUtils.isNotBlank(filename) ? filename : itemName;

            try (final InputStream stream = inputStream) {
                LOG.debug("Reads image content from the field ; name: '{}'.", name);

                if (logo) {
                    size[0] = logoManager.updateLogo(stream, name);
                } else {
                    size[0] = fileStorageProvider.copy(stream, name, StandardCopyOption.REPLACE_EXISTING);
                }

                response.setStatus(Response.SC_ACCEPTED);

                // FIXME : perhaps keep the response above for error catching
                // response.getWriter().write("ok");
                LOG.debug("File '{}' upload has been successfully processed.", name);
            }
        }
    });

    return size[0];
}