Java Code Examples for java.nio.file.Files#move()

The following examples show how to use java.nio.file.Files#move() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BackupService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private static void updateApplicationDb(@Nullable Db restoreDb, File path) {
   try {
      File appDbPath = DbService.getApplicationDbPath();

      Path updatedDbPath = FileSystems.getDefault().getPath(path.getAbsolutePath());
      Path existingDbPath = FileSystems.getDefault().getPath(appDbPath.getAbsolutePath());

      Files.move(updatedDbPath, existingDbPath, StandardCopyOption.REPLACE_EXISTING);

      if (restoreDb != null) {
         restoreDb.close();
      }

      DbService.reloadApplicationDb();
   } catch (IOException ex) {
      log.warn("could not overwrite application database with backup copy:", ex);
      throw new RuntimeException(ex);
   }
}
 
Example 2
Source File: Utility.java    From md2html with MIT License 6 votes vote down vote up
public static void clean(String inputPath, String outputPath) {
    if (!Config.hasIconv) {
        return;
    }
    try {
        File temp = File.createTempFile("iconv-"+outputPath.hashCode()+"-", ".txt");
        System.out.println(temp.getCanonicalPath());
        ProcessBuilder pb = new ProcessBuilder().command(new String[]{
                "iconv",
                "-f", "utf-8",
                "-t", "utf-8",
                "-c", inputPath
        });
        pb.redirectOutput(temp);
        Process p = pb.start();
        p.waitFor(5, TimeUnit.SECONDS);
        Files.move(temp.toPath(), new File(outputPath).toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (Exception e) {
    }
}
 
Example 3
Source File: FilesMoveController.java    From MyBox with Apache License 2.0 6 votes vote down vote up
@Override
public String handleFile(File srcFile, File targetPath) {
    try {
        countHandling(srcFile);
        File target = makeTargetFile(srcFile, targetPath);
        if (target == null) {
            return AppVariables.message("Skip");
        }
        Path path = Files.move(Paths.get(srcFile.getAbsolutePath()), Paths.get(target.getAbsolutePath()),
                StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
        if (path == null) {
            return AppVariables.message("Failed");
        }
        if (verboseCheck == null || verboseCheck.isSelected()) {
            updateLogs(message("FileMovedSuccessfully") + ": " + path.toString());
        }
        return AppVariables.message("Successful");
    } catch (Exception e) {
        logger.error(e.toString());
        return AppVariables.message("Failed");
    }
}
 
Example 4
Source File: ServerConfigurationManager.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * backup the current server configuration file
 *
 * @param fileName file name
 * @throws IOException
 */
private void backupConfiguration(String fileName) throws IOException {
    //restore backup configuration
    String carbonHome = System.getProperty(ServerConstants.CARBON_HOME);
    String confDir = Paths.get(carbonHome, "conf").toString();
    String axis2Xml = "axis2";
    if (fileName.contains(axis2Xml)) {
        confDir = Paths.get(confDir, "axis2").toString();
    }
    originalConfig = Paths.get(confDir, fileName).toFile();
    backUpConfig = Paths.get(confDir, fileName + ".backup").toFile();

    Files.move(originalConfig.toPath(), backUpConfig.toPath(), StandardCopyOption.REPLACE_EXISTING);

    if (originalConfig.exists()) {
        throw new IOException(
                "Failed to rename file from " + originalConfig.getName() + "to" + backUpConfig.getName());
    }

    configData.add(new ConfigData(backUpConfig, originalConfig));
}
 
Example 5
Source File: TailableFileTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Test
void testRestoreStateOfRotatedFile() throws Exception {
    tailableFile.tail(buffy, logListener, 1);
    assertThat(logListener.lines).containsExactly("foo");
    assertThat(logListener.lines.get(0)).isEqualTo("foo");
    tailableFile.ack();
    tailableFile.close();
    logListener.lines.clear();

    Path rotatedLog = logFile.toPath().resolveSibling("log-1.log");
    Files.move(logFile.toPath(), rotatedLog);
    try {
        Files.write(logFile.toPath(), List.of("quux", "corge"), CREATE_NEW);

        setUp();
        tailableFile.tail(buffy, logListener, 10);
        assertThat(logListener.lines).containsExactly(
            // continue reading form old rotated log
            "bar", "baz", "qux",
            // resume with new log
            "quux", "corge");
    } finally {
        Files.move(rotatedLog, logFile.toPath(), REPLACE_EXISTING);
    }
}
 
Example 6
Source File: ServerConfigurationManager.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * restore to a last configuration and restart the server
 */
public void restoreToLastMIConfiguration() throws IOException, AutomationUtilException {

    // shut down the server before applying configs to avoid file lock issues.
    CarbonServerExtension.shutdownServer();

    for (ConfigData data : configData) {
        Files.move(data.getBackupConfig().toPath(), data.getOriginalConfig().toPath(),
                   StandardCopyOption.REPLACE_EXISTING);

        if (data.getBackupConfig().exists()) {
            throw new IOException(
                    "File rename from " + data.getBackupConfig() + "to " + data.getOriginalConfig() + "fails");
        }
    }
    CarbonServerExtension.startServer();
}
 
Example 7
Source File: Page2010Converter.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
@Deprecated
public static File updatePageFormatSingleFileOld(File input, String backupDirStr) throws IOException {
	File backupDir = new File(backupDirStr);
	if(!backupDir.exists()){
		backupDir.mkdirs();
	}
	
	//output
	File tmpFile = new File(input.getAbsolutePath() + ".tmp"); 

	//do conversion
	convert(input, tmpFile);
	
	//move input to backup path
	File backup = new File(backupDir, input.getName());
	Files.move(input.toPath(), backup.toPath());
	//move output into original file's place
	Files.move(tmpFile.toPath(), input.toPath());
	
	return input;
}
 
Example 8
Source File: DflCache.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private static void expunge(Path p, KerberosTime currTime)
        throws IOException {
    Path p2 = Files.createTempFile(p.getParent(), "rcache", null);
    try (SeekableByteChannel oldChan = Files.newByteChannel(p);
            SeekableByteChannel newChan = createNoClose(p2)) {
        long timeLimit = currTime.getSeconds() - readHeader(oldChan);
        while (true) {
            try {
                AuthTime at = AuthTime.readFrom(oldChan);
                if (at.ctime > timeLimit) {
                    ByteBuffer bb = ByteBuffer.wrap(at.encode(true));
                    newChan.write(bb);
                }
            } catch (BufferUnderflowException e) {
                break;
            }
        }
    }
    makeMine(p2);
    Files.move(p2, p,
            StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.ATOMIC_MOVE);
}
 
Example 9
Source File: Util.java    From ecosys with Apache License 2.0 6 votes vote down vote up
public static File getClientLogFile(String file, String username, String serverip,
    boolean rotate) throws IOException {
  if (Util.LOG_DIR == null) {
    throw new IOException("LogDir is null");
  }

  String filename = Util.LOG_DIR + "/" + file + ".";
  filename += Math.abs((username + "." + serverip).hashCode()) % 1000000;
  File f = new File(filename);
  if (!f.getParentFile().isDirectory()) {
    f.getParentFile().mkdirs();
  }

  if (!f.exists()) {
    //create file if it does not exist
    f.createNewFile();
  } else if (rotate && f.length() > Constant.LogRotateSize) {
    // rotate log file when file is large than 500M
    long current = System.currentTimeMillis();
    // copy the log to a new file with timestamp
    String LogCopy = filename + "." + current / 1000;
    Files.move(f.toPath(), Paths.get(LogCopy), StandardCopyOption.REPLACE_EXISTING);
  }

  return f;
}
 
Example 10
Source File: ShardRecoveryManager.java    From presto with Apache License 2.0 6 votes vote down vote up
private void quarantineFile(UUID shardUuid, File file, String message)
{
    File quarantine = new File(storageService.getQuarantineFile(shardUuid).getPath() + ".corrupt");
    if (quarantine.exists()) {
        log.warn("%s Quarantine already exists: %s", message, quarantine);
        return;
    }

    log.error("%s Quarantining corrupt file: %s", message, quarantine);
    try {
        Files.move(file.toPath(), quarantine.toPath(), ATOMIC_MOVE);
    }
    catch (IOException e) {
        log.warn(e, "Quarantine of corrupt file failed: " + quarantine);
        file.delete();
    }
}
 
Example 11
Source File: BackupHandler.java    From ha-bridge with Apache License 2.0 6 votes vote down vote up
public String restoreBackup(String aFilename) {
      log.debug("Restore backup repository: " + aFilename);
try {
	Path target = null;
	if(Files.exists(repositoryPath)) {
       	DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		target = FileSystems.getDefault().getPath(repositoryPath.getParent().toString(), defaultName + dateFormat.format(Calendar.getInstance().getTime()) + fileExtension);
		Files.move(repositoryPath, target);
	}
	Files.copy(FileSystems.getDefault().getPath(repositoryPath.getParent().toString(), aFilename), repositoryPath, StandardCopyOption.COPY_ATTRIBUTES);
} catch (IOException e) {
	log.error("Error restoring the file: " + aFilename + " message: " + e.getMessage(), e);
	return null;
}
      return aFilename;
  }
 
Example 12
Source File: JournaledCoalescer.java    From emissary with Apache License 2.0 5 votes vote down vote up
protected void renameToError(Path path) {
    try {
        Path bgerror = Paths.get(path.toString() + ERROR_EXT);
        Files.move(path, bgerror);
    } catch (IOException ex) {
        LOG.warn("Unable to rename file {}.", path.toString(), ex);
    }
}
 
Example 13
Source File: CatalogTestUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void deleteJAXPProps() throws IOException {
    Path filePath = getJAXPPropsPath();
    Path bakPath = filePath.resolveSibling(JAXP_PROPS_BAK);
    System.out.println("Removing file " + filePath +
            ", restoring old version from " + bakPath + ".");
    Files.delete(filePath);
    if (Files.exists(bakPath)) {
        Files.move(bakPath, filePath);
    }
}
 
Example 14
Source File: NBTIO.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public static void safeWrite(CompoundTag tag, File file) throws IOException {
    File tmpFile = new File(file.getAbsolutePath() + "_tmp");
    if (tmpFile.exists()) {
        tmpFile.delete();
    }
    write(tag, tmpFile);
    Files.move(tmpFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
}
 
Example 15
Source File: CoredumpHandlerTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void coredump_enqueue_test() throws IOException {
    final Path crashPathOnHost = fileSystem.getPath("/home/docker/container-1/some/crash/path");
    final Path processingDir = fileSystem.getPath("/home/docker/container-1/some/other/processing");

    Files.createDirectories(crashPathOnHost);
    createFileAged(crashPathOnHost.resolve(".bash.core.431"), Duration.ZERO);

    assertFolderContents(crashPathOnHost, ".bash.core.431");
    Optional<Path> enqueuedPath = coredumpHandler.enqueueCoredump(crashPathOnHost, processingDir);
    assertEquals(Optional.empty(), enqueuedPath);

    // bash.core.431 finished writing... and 2 more have since been written
    Files.move(crashPathOnHost.resolve(".bash.core.431"), crashPathOnHost.resolve("bash.core.431"));
    createFileAged(crashPathOnHost.resolve("vespa-proton.core.119"), Duration.ofMinutes(10));
    createFileAged(crashPathOnHost.resolve("vespa-slobrok.core.673"), Duration.ofMinutes(5));

    when(coredumpIdSupplier.get()).thenReturn("id-123").thenReturn("id-321");
    enqueuedPath = coredumpHandler.enqueueCoredump(crashPathOnHost, processingDir);
    assertEquals(Optional.of(processingDir.resolve("id-123")), enqueuedPath);
    assertFolderContents(crashPathOnHost, "bash.core.431", "vespa-slobrok.core.673");
    assertFolderContents(processingDir, "id-123");
    assertFolderContents(processingDir.resolve("id-123"), "dump_vespa-proton.core.119");
    verify(coredumpIdSupplier, times(1)).get();

    // Enqueue another
    enqueuedPath = coredumpHandler.enqueueCoredump(crashPathOnHost, processingDir);
    assertEquals(Optional.of(processingDir.resolve("id-321")), enqueuedPath);
    assertFolderContents(crashPathOnHost, "bash.core.431");
    assertFolderContents(processingDir, "id-123", "id-321");
    assertFolderContents(processingDir.resolve("id-321"), "dump_vespa-slobrok.core.673");
    verify(coredumpIdSupplier, times(2)).get();
}
 
Example 16
Source File: ConfigurationPersisterFactory.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void successfulBoot() throws ConfigurationPersistenceException {
    if (successfulBoot.compareAndSet(false, true)) {
        try {
            Files.move(bootFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            HostControllerLogger.ROOT_LOGGER.cannotRenameCachedDomainXmlOnBoot(bootFile.getName(), file.getName(), e.getMessage());
            throw new ConfigurationPersistenceException(e);
        }
    }
}
 
Example 17
Source File: CodebaseTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {
    RegistryVM rmiregistry = null;
    JavaVM client = null;
    try {
        File src = new File(System.getProperty("test.classes", "."), "testPkg");
        File dest = new File(System.getProperty("user.dir", "."), "testPkg");
        Files.move(src.toPath(), dest.toPath(),
                StandardCopyOption.REPLACE_EXISTING);

        File rmiregistryDir =
            new File(System.getProperty("user.dir", "."), "rmi_tmp");
        rmiregistryDir.mkdirs();
        rmiregistry = RegistryVM.createRegistryVMWithRunner(
                "RMIRegistryRunner",
                " -Djava.rmi.server.useCodebaseOnly=false"
                + " -Duser.dir=" + rmiregistryDir.getAbsolutePath());
        rmiregistry.start();
        int port = rmiregistry.getPort();

        File srcReadTest = new File(System.getProperty("test.classes", "."),
                                "RegistryLookup.class");
        File destReadTest = new File(System.getProperty("user.dir", "."),
                                "RegistryLookup.class");
        Files.move(srcReadTest.toPath(), destReadTest.toPath(),
                                StandardCopyOption.REPLACE_EXISTING);

        File codebase = new File(System.getProperty("user.dir", "."));
        client = new JavaVM("RegistryLookup",
                " -Djava.rmi.server.codebase=" + codebase.toURI().toURL()
                + " -cp ." + File.pathSeparator + System.getProperty("test.class.path"),
                Integer.toString(port));
        int exit = client.execute();
        if (exit == RegistryLookup.EXIT_FAIL) {
            throw new RuntimeException("Test Fails");
        }
    } finally {
        if (rmiregistry != null) {
            rmiregistry.cleanup();
        }
        if (client != null) {
            client.cleanup();
        }
    }
}
 
Example 18
Source File: NodeProjectGroup.java    From netbeans-mmd-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public void valueForPathChanged(@Nonnull final TreePath path, @Nonnull final Object newValue) {
  String newFileName = String.valueOf(newValue);

  if (FILE_NAME.matcher(newFileName).matches()) {
    final Object last = path.getLastPathComponent();
    if (last instanceof NodeFileOrFolder) {
      final NodeFileOrFolder editedNode = (NodeFileOrFolder) last;

      final String oldName = editedNode.toString();

      if (!oldName.equals(newFileName)) {
        final File origFile = ((NodeFileOrFolder) last).makeFileForNode();
        final String oldExtension = FilenameUtils.getExtension(oldName);
        final String newExtension = FilenameUtils.getExtension(newFileName);

        if (!oldExtension.equals(newExtension)) {
          if (DialogProviderManager.getInstance().getDialogProvider().msgConfirmYesNo(Main.getApplicationFrame(), "Changed extension", String.format("You have changed extension! Restore old extension '%s'?", oldExtension))) {
            newFileName = FilenameUtils.getBaseName(newFileName) + (oldExtension.isEmpty() ? "" : '.' + oldExtension); //NOI18N
          }
        }

        if (origFile != null) {
          final File newFile = new File(origFile.getParentFile(), newFileName);

          if (!editedNode.isLeaf() && !context.safeCloseEditorsForFile(origFile)) {
            return;
          }

          try {

            boolean doIt = true;

            List<File> affectedFiles = null;

            final NodeProject project = editedNode.findProject();
            if (project != null) {
              affectedFiles = project.findAffectedFiles(origFile);
              if (!affectedFiles.isEmpty()) {
                affectedFiles = UiUtils.showSelectAffectedFiles(affectedFiles);
                if (affectedFiles == null) {
                  doIt = false;
                } else {
                  affectedFiles = project.replaceAllLinksToFile(affectedFiles, origFile, newFile);
                }
              }
            }

            if (doIt) {
              Files.move(origFile.toPath(), newFile.toPath());
              editedNode.setName(newFile.getName());

              final TreeModelEvent renamedEvent = new TreeModelEvent(this, editedNode.makeTreePath());
              for (final TreeModelListener l : listeners) {
                l.treeNodesChanged(renamedEvent);
              }

              editedNode.fireNotifySubtreeChanged(this, listeners);

              this.context.notifyFileRenamed(affectedFiles, origFile, newFile);
            }
          } catch (IOException ex) {
            LOGGER.error("Can't rename file", ex); //NOI18N
            DialogProviderManager.getInstance().getDialogProvider().msgError(Main.getApplicationFrame(), "Can't rename file to '" + newValue + "\'");
          }
        }
      }
    }
  } else {
    DialogProviderManager.getInstance().getDialogProvider().msgError(Main.getApplicationFrame(), "Inapropriate file name '" + newFileName + "'!");
  }
}
 
Example 19
Source File: FaultyFileSystem.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void move(Path source, Path target, CopyOption... options) throws IOException {
    triggerEx(source, "move");
    Files.move(unwrap(source), unwrap(target), options);
}
 
Example 20
Source File: ToolBox.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Moves a file.
 * If the given destination exists and is a directory, the file will be moved
 * to that directory.  Otherwise, the file will be moved to the destination,
 * possibly overwriting any existing file.
 * <p>Similar to the shell "mv" command: {@code mv from to}.
 * @param from the file to be moved
 * @param to where to move the file
 * @throws IOException if an error occurred while moving the file
 */
public void moveFile(Path from, Path to) throws IOException {
    if (Files.isDirectory(to)) {
        to = to.resolve(from.getFileName());
    } else {
        Files.createDirectories(to.getParent());
    }
    Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
}