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:phex.performance.TestFileCopy.java

/**
 * Copys the source file to the destination file. Old contents of the
 * destination file will be overwritten.
 *
 * @deprecated use org.apache.commons.io.FileUtils.copyFile( source, destination );
 *///from w w  w. ja v  a 2s . c  om
public static void copyFile(File source, File destination) throws IOException {
    Files.copy(Paths.get(source.toURI()), Paths.get(destination.toURI()), StandardCopyOption.REPLACE_EXISTING);

    //        // open files
    //        BufferedInputStream inStream = new BufferedInputStream(
    //            new FileInputStream( source ) );
    //        BufferedOutputStream outStream = new BufferedOutputStream(
    //            new FileOutputStream( destination ) );
    //
    //        byte[] buffer = new byte[ (int)Math.min( BUFFER_LENGTH, source.length() + 1) ];
    //        int length;
    //        while ( true )
    //        {
    //            // read the min value of the buffer length or the value left to read
    //            length = inStream.read( buffer, 0, buffer.length );
    //            // end of stream
    //            if ( length == -1 )
    //            {
    //                break;
    //            }
    //
    //            outStream.write( buffer, 0, length );
    //        }
    //        outStream.close();
    //        inStream.close();
}

From source file:pl.baczkowicz.mqttspy.configuration.ConfigurationUtils.java

public static boolean createDefaultConfigFromFile(final File orig) {
    try {//from   w  ww . j av  a 2 s .com
        final File dest = ConfigurationManager.getDefaultConfigurationFile();

        dest.mkdirs();
        Files.copy(orig.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);

        return true;

    } catch (IOException e) {
        // TODO: show warning dialog for invalid
        logger.error("Cannot copy configuration file", e);
    }

    return false;
}

From source file:com.liferay.sync.engine.documentlibrary.handler.DownloadFileHandler.java

@Override
protected void doHandleResponse(HttpResponse httpResponse) throws Exception {

    InputStream inputStream = null;

    try {//  w  ww .j  ava 2 s  .c o  m
        SyncFile syncFile = (SyncFile) getParameterValue("syncFile");

        Path filePath = Paths.get(syncFile.getFilePathName());

        HttpEntity httpEntity = httpResponse.getEntity();

        inputStream = httpEntity.getContent();

        Path tempFilePath = Files.createTempFile(String.valueOf(filePath.getFileName()), ".tmp");

        if (Files.exists(filePath)) {
            Files.copy(filePath, tempFilePath);
        }

        if ((Boolean) getParameterValue("patch")) {
            IODeltaUtil.patch(tempFilePath, inputStream);
        } else {
            Files.copy(inputStream, tempFilePath, StandardCopyOption.REPLACE_EXISTING);
        }

        syncFile.setFileKey(FileUtil.getFileKey(tempFilePath));
        syncFile.setState(SyncFile.STATE_SYNCED);
        syncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED);

        SyncFileService.update(syncFile);

        Files.move(tempFilePath, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    } finally {
        StreamUtil.cleanUp(inputStream);
    }
}

From source file:org.apache.gobblin.hive.avro.HiveAvroSerDeManagerTest.java

@BeforeClass
public void setUp() throws IOException {
    FileSystem fs = FileSystem.getLocal(new Configuration());
    this.testBasePath = new Path("testdir");
    fs.delete(this.testBasePath, true);
    fs.delete(this.testBasePath, true);

    fs.mkdirs(this.testBasePath);

    Files.copy(this.getClass().getResourceAsStream("/test-hive-table/hive-test.avro"),
            Paths.get(this.testBasePath.toString(), "hive-test.avro"), StandardCopyOption.REPLACE_EXISTING);
}

From source file:org.cloudfoundry.dependency.resource.InAction.java

protected final String writeArtifact(String artifactName, InputStream content) {
    try (InputStream in = content) {
        Path artifactFile = Files.createDirectories(this.destination).resolve(artifactName);
        Files.copy(in, artifactFile, StandardCopyOption.REPLACE_EXISTING);
        return getSha256(artifactFile);
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }// w  w  w. ja  v a 2s .  com
}

From source file:com.stimulus.archiva.domain.Settings.java

public static void saveProperties(final String name, String intro, Settings prop, String charset)
        throws ConfigurationException {
    File f = null;//  w w w.  jav  a2 s .  co m
    try {
        // if the disk is full we dont want to end up in a situation where we delete
        // server.conf file
        f = File.createTempFile("server_conf", ".tmp");
        prop.store(intro, new FileOutputStream(f), charset);

    } catch (Exception e) {
        if (f != null)
            f.delete();
        throw new ConfigurationException("failed to save properties. cause:" + e.toString(), e, logger);
    }
    File newFile = new File(name);
    newFile.delete();
    //Mod start Seolhwa.kim 2017-04-13
    //f.renameTo(newFile);

    try {
        logger.debug("####################################### Call Files.move");
        Files.move(Paths.get(f.getAbsolutePath()), Paths.get(newFile.getAbsolutePath()),
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        logger.debug("####################################### Call Files.move fails");
        e.printStackTrace();
    }

    //Mod end Seolhwa.kim 2017-04-13
}

From source file:JMeterProcessing.JMeterPropertiesGenerator.java

private static void generatePropertiesFile(Map<String, Long> idValuesMap) throws IOException {
    String propertiesOutputDir = System.getProperty("properties.output.dir");
    File original = new File(propertiesOutputDir + "/testray.jmeter.full.depth.properties");
    File generated = new File(propertiesOutputDir + "/testray.jmeter.properties");

    Files.copy(original.toPath(), generated.toPath(), StandardCopyOption.REPLACE_EXISTING);

    try (BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(generated, true), "utf-8"))) {

        printProperties(writer, idValuesMap);

        writer.flush();/* ww w .j  a v a 2  s. c  o m*/
    }
}

From source file:com.xiaomi.linden.hadoop.indexing.LindenMapredTest.java

@Test
public void TestMapper() throws IOException {
    try {//from   www .  j  a va2s.co  m
        String propertiesFilePath = LindenMapredTest.class.getClassLoader().getResource("linden.properties")
                .getFile();
        Files.copy(new File(propertiesFilePath).toPath(), Paths.get("lindenProperties"),
                StandardCopyOption.REPLACE_EXISTING);
        String schemaFilePath = LindenMapredTest.class.getClassLoader().getResource("schema.xml").getFile();
        Files.copy(new File(schemaFilePath).toPath(), Paths.get("lindenSchema"),
                StandardCopyOption.REPLACE_EXISTING);
        String json = "{\"id\":0,\"groupid\":\"0\",\"tags\":\"hybrid,leather,moon-roof,reliable\",\"category\":\"compact\",\"mileage\":14900,\"price\":7500,\"contents\":\"yellow compact hybrid leather moon-roof reliable u.s.a. florida tampa asian acura 1.6el \",\"color\":\"yellow\",\"year\":1994,\"makemodel\":\"asian/acura/1.6el\",\"city\":\"u.s.a./florida/tampa\"}";
        mDriver.withInput(new LongWritable(1L), new Text(json.getBytes()));
        mDriver.run();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.assertTrue(false);
    } finally {
        FileUtils.deleteQuietly(Paths.get("lindenProperties").toFile());
        FileUtils.deleteQuietly(Paths.get("lindenSchema").toFile());
    }
}

From source file:com.skynetcomputing.skynetclient.WorkManagerTest.java

/**
 * Test of start method, of class WorkManager.
 *
 * @throws java.io.IOException/*from   ww w .  ja v a2 s.  c  om*/
 * @throws java.lang.InterruptedException
 */
@Test
public void testStart() throws IOException, InterruptedException {
    IConnectionMgr conn = new IConnectionMgr() {
        @Override
        public void sendFile(File aFile) {
            try {
                Files.copy(aFile.toPath(), new File(LOCAL_INPUT_DIR + aFile.getName()).toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException ex) {
                Logger.getLogger(WorkManagerTest.class.getName()).log(Level.SEVERE, "Error sending file", ex);
            }
        }

        @Override
        public void notifyJarOKNOK(boolean isOK) throws IOException {
            assertTrue("Checking Jar presence", isOK);
        }

        @Override
        public void notifyTaskCompleted() throws IOException {
            Logger.getLogger(WorkManagerTest.class.getName()).log(Level.INFO, "Task Completed");
            synchronized (isRunning) {
                isRunning.set(false);
                isRunning.notifyAll();
            }
        }

        @Override
        public void start(InetSocketAddress serverAddress) {
            System.out.println("Fake start listening..");
        }

        @Override
        public boolean isSendingFiles() {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void notifyTaskStarting() throws IOException {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    };

    WorkManager workMgr = new WorkManager(conn, ROOT_DIR);
    // Read only, should not be used for saving files
    PersistenceManager persistMgr = new PersistenceManager(ROOT_DIR);

    File testDir = new File(MANDELTASK_DIR);
    File jobJar = FileUtils.listFiles(testDir, new String[] { "jar" }, false).iterator().next();
    workMgr.onJarReceived(jobJar);
    File localDir = new File(LOCAL_INPUT_DIR);
    FileUtils.deleteDirectory(localDir);
    localDir.mkdirs();
    for (File f : testDir.listFiles()) {
        Files.copy(f.toPath(), new File(LOCAL_INPUT_DIR + f.getName()).toPath(),
                StandardCopyOption.REPLACE_EXISTING);
    }

    for (int i = 1; i <= 4; i++) {
        isRunning.getAndSet(true);
        File taskJson = new File(localDir, i + ".task");
        File jobData = new File(localDir, i + ".data");

        workMgr.onTaskReceived(taskJson);
        workMgr.onDataReceived(jobData);

        synchronized (isRunning) {
            while (isRunning.get()) {
                isRunning.wait();
            }
        }
    }

    isRunning.getAndSet(true);

    File combineTaskFile = new File(localDir, "20" + SrzTask.EXT);
    workMgr.onTaskReceived(combineTaskFile);

    SrzTask combineTask = persistMgr.readTaskFile(combineTaskFile);
    for (int id : combineTask.getDependencies()) {
        workMgr.onDataReceived(new File(localDir, id + SrzData.EXT));
    }

    synchronized (isRunning) {
        while (isRunning.get()) {
            isRunning.wait();
        }
    }

    Logger.getLogger(WorkManagerTest.class.getName()).log(Level.INFO, "Test Finished");
}

From source file:org.apdplat.superword.tools.JavaCodeAnalyzer.java

public static Map<String, AtomicInteger> parseZip(String zipFile) {
    LOGGER.info("?ZIP" + zipFile);
    Map<String, AtomicInteger> data = new HashMap<>();
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile),
            JavaCodeAnalyzer.class.getClassLoader())) {
        for (Path path : fs.getRootDirectories()) {
            LOGGER.info("?" + path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                @Override// w  w w  .  ja v a2  s  . co  m
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    LOGGER.info("?" + file);
                    // ?
                    Path temp = Paths.get("target/java-source-code.txt");
                    Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                    Map<String, AtomicInteger> r = parseFile(temp.toFile().getAbsolutePath());
                    r.keySet().forEach(k -> {
                        data.putIfAbsent(k, new AtomicInteger());
                        data.get(k).addAndGet(r.get(k).get());
                    });
                    r.clear();
                    return FileVisitResult.CONTINUE;
                }

            });
        }
    } catch (Exception e) {
        LOGGER.error("?ZIP", e);
    }
    return data;
}