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

The following are Jave code examples for showing how to use move() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: iron   File: FileTransactionStore.java   View Source Code Vote up 7 votes
@Override
public OutputStream createTransactionOutput() throws IOException {
    Path tmpFile = m_transactionTmpDir.resolve(getFileName(m_tmpCounter.getAndIncrement(), TX_EXT));

    return new BufferedOutputStream(Files.newOutputStream(tmpFile)) {
        @Override
        public void close() throws IOException {
            super.close();
            synchronized (m_commitLock) {
                long transactionId = m_nextTxId++;
                Path txFile = getTxFile(transactionId);

                Files.move(tmpFile, txFile);
                m_commitLock.notifyAll();
            }
        }
    };
}
 
Example 2
Project: marathonv5   File: FileResource.java   View Source Code Vote up 7 votes
@Override public Resource rename(String text) {
    try {
        File sourceFile = path.toFile();
        File destinationFile = path.resolveSibling(text).toFile();
        Path moved;
        if (!sourceFile.getParent().equals(destinationFile.getParent())) {
            moved = Files.move(path, path.resolveSibling(text));
        } else {
            sourceFile.renameTo(destinationFile);
            moved = destinationFile.toPath();
        }
        FileResource to = new FileResource(moved.toFile());
        Event.fireEvent(this, new ResourceModificationEvent(ResourceModificationEvent.MOVED, this, to));
        return to;
    } catch (IOException e) {
        FXUIUtils.showMessageDialog(null, "Unable to rename file: " + e.getMessage(), e.getClass().getName(), AlertType.ERROR);
        return null;
    }
}
 
Example 3
Project: Cognizant-Intelligent-Test-Scripter   File: FileUtils.java   View Source Code Vote up 6 votes
public static Boolean renameFile(String fromFile, String toName) {
    try {
        File src = new File(fromFile);
        if (src.exists()) {
            File target = new File(src.getParent(), toName);
            if (target.exists()) {
                LOGGER.log(Level.INFO, "A File with Name '{1}' already exists, failed to rename '{0}'",
                        new Object[]{fromFile, toName});
                return false;
            }
            Files.move(src.toPath(), target.toPath());
        }
    } catch (IOException ex) {
        Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    LOGGER.log(Level.INFO, "{0} Renamed to {1}", new Object[]{fromFile, toName});
    return true;
}
 
Example 4
Project: openjdk-jdk10   File: JmodTask.java   View Source Code Vote up 6 votes
private boolean create() throws IOException {
    JmodFileWriter jmod = new JmodFileWriter();

    // create jmod with temporary name to avoid it being examined
    // when scanning the module path
    Path target = options.jmodFile;
    Path tempTarget = jmodTempFilePath(target);
    try {
        try (JmodOutputStream jos = JmodOutputStream.newOutputStream(tempTarget)) {
            jmod.write(jos);
        }
        Files.move(tempTarget, target);
    } catch (Exception e) {
        try {
            Files.deleteIfExists(tempTarget);
        } catch (IOException ioe) {
            e.addSuppressed(ioe);
        }
        throw e;
    }
    return true;
}
 
Example 5
Project: openjdk-jdk10   File: ZipFSTester.java   View Source Code Vote up 6 votes
private static void z2zmove(FileSystem src, FileSystem dst, String path)
    throws IOException
{
    Path srcPath = src.getPath(path);
    Path dstPath = dst.getPath(path);

    if (Files.isDirectory(srcPath)) {
        if (!Files.exists(dstPath))
            mkdirs(dstPath);
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(srcPath)) {
            for (Path child : ds) {
                z2zmove(src, dst,
                        path + (path.endsWith("/")?"":"/") + child.getFileName());
            }
        }
    } else {
        //System.out.println("moving..." + path);
        Path parent = dstPath.getParent();
        if (parent != null && Files.notExists(parent))
            mkdirs(parent);
        Files.move(srcPath, dstPath);
    }
}
 
Example 6
Project: centraldogma   File: FileBasedSessionDAO.java   View Source Code Vote up 6 votes
@Override
public void update(Session session) {
    final String sessionId = ensureStringSessionId(session);
    final Path oldPath = sessionId2Path(sessionId);
    if (!Files.exists(oldPath)) {
        throw new UnknownSessionException(sessionId);
    }

    try {
        final Path newPath = Files.createTempFile(tmpDir, null, null);
        Files.write(newPath, serialize(session));
        Files.move(newPath, oldPath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new SerializationException(e);
    }
}
 
Example 7
Project: openjdk-jdk10   File: CatalogTestUtils.java   View Source Code Vote up 5 votes
static void generateJAXPProps(String content) throws IOException {
    Path filePath = getJAXPPropsPath();
    Path bakPath = filePath.resolveSibling(JAXP_PROPS_BAK);
    System.out.println("Creating new file " + filePath +
        ", saving old version to " + bakPath + ".");
    if (Files.exists(filePath) && !Files.exists(bakPath)) {
        Files.move(filePath, bakPath);
    }

    Files.write(filePath, content.getBytes());
}
 
Example 8
Project: uppercore   File: ReplaceUpdateMethod.java   View Source Code Vote up 5 votes
@Override
public void update(File updateFile, Plugin plugin) throws IOException {
    Path src = updateFile.toPath();
    Path trg = UpdateMethod.getPluginFile(plugin).toPath();
    try {
        Files.move(src, trg, ATOMIC_MOVE);
    } catch (Exception e) {
        //Fallback
        Files.move(src, trg, REPLACE_EXISTING);
    }
}
 
Example 9
Project: powsybl-core   File: ZipFileDataSource.java   View Source Code Vote up 5 votes
@Override
public void close() throws IOException {
    if (!closed) {
        // close new entry
        os.closeEntry();

        // copy existing entries
        if (Files.exists(zipFilePath)) {
            try (ZipFile zipFile = new ZipFile(zipFilePath)) {
                Enumeration<? extends ZipEntry> e = zipFile.entries();
                while (e.hasMoreElements()) {
                    ZipEntry zipEntry = e.nextElement();
                    if (!zipEntry.getName().equals(fileName)) {
                        os.putNextEntry(zipEntry);
                        try (InputStream zis = zipFile.getInputStream(zipEntry.getName())) {
                            ByteStreams.copy(zis, os);
                        }
                        os.closeEntry();
                    }
                }
            }
        }

        // close zip
        super.close();

        // swap with tmp zip
        Path tmpZipFilePath = getTmpZipFilePath(zipFilePath);
        Files.move(tmpZipFilePath, zipFilePath, StandardCopyOption.REPLACE_EXISTING);

        closed = true;
    }
}
 
Example 10
Project: Coconut-IDE   File: RenameFolderPresenter.java   View Source Code Vote up 5 votes
@SneakyThrows(IOException.class)
private void renameFile() {
    Path path = places.closeAndGetRenameFolderPlace();
    String nameOfFolder = name.getText();
    Path pathRename = path.getParent().resolve(nameOfFolder);
    Files.move(path, pathRename);
}
 
Example 11
Project: java-tutorial   File: PathMoveTest.java   View Source Code Vote up 5 votes
public static void main(String[] args) {
    Path src = Paths.get(System.getProperty("user.home") + "myfile.txt");
    Path dest = Paths.get(System.getProperty("user.home") + "/test/myfile.txt");

    try {
        // 如果目标文件存在则先删除,防止干扰move的结果
        Files.delete(dest);
        Files.move(src, dest, REPLACE_EXISTING); // |\longremark{可以尝试去掉REPLACE\_EXISTING参数看看运行结果有什么不同?}|
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("move file success? " + Files.exists(dest));
}
 
Example 12
Project: IOManager   File: IOManager.java   View Source Code Vote up 5 votes
/**
 * Move files (or directories) to specified path
 * @param originPath String that contains the original file/folder to be moved
 * @param destinationPath String that contains the destination path to save the old file/directories
 * @param replaceExisting boolean that indicates if replace any existing file/directory if duplicated
 */
public static void moveFilesDirs(String originPath, String destinationPath, boolean replaceExisting) {
    try {
        if (replaceExisting)
            Files.move(Paths.get(originPath), Paths.get(destinationPath), REPLACE_EXISTING);
        else
            Files.move(Paths.get(originPath), Paths.get(destinationPath));
    } catch (IOException e) {
        IO.write("There was an error while trying to move the file/dir specified. Full trace: \n");
        e.printStackTrace();
    }
}
 
Example 13
Project: openjdk-jdk10   File: Security.java   View Source Code Vote up 5 votes
static void movefile(String f) throws IOException {
    Path src = Paths.get(testclasses, f);
    Path dest = subdir.toPath().resolve(f);
    if (!dest.toFile().exists()) {
        System.out.printf("moving %s to %s\n", src.toString(), dest.toString());
        Files.move(src, dest,  StandardCopyOption.REPLACE_EXISTING);
    } else if (src.toFile().exists()) {
        System.out.printf("%s exists, deleting %s\n", dest.toString(), src.toString());
        Files.delete(src);
    } else {
        System.out.printf("NOT moving %s to %s\n", src.toString(), dest.toString());
    }
}
 
Example 14
Project: openjdk-jdk10   File: SplitPackage.java   View Source Code Vote up 5 votes
@BeforeTest
private void setup() throws Exception {
    Files.createDirectory(BAR_DIR);

    Path pkgDir = Paths.get("p");
    // compile classes in package p
    assertTrue(CompilerUtils.compile(SRC_DIR.resolve(pkgDir), BAR_DIR));

    // move p.Foo to a different directory
    Path foo = pkgDir.resolve("Foo.class");
    Files.createDirectories(FOO_DIR.resolve(pkgDir));
    Files.move(BAR_DIR.resolve(foo), FOO_DIR.resolve(foo),
               StandardCopyOption.REPLACE_EXISTING);
}
 
Example 15
Project: minikube-build-tools-for-java   File: CacheWriter.java   View Source Code Vote up 5 votes
public CachedLayer writeLayer(UnwrittenLayer layer) throws IOException {
  // Writes to a temporary file first because the UnwrittenLayer needs to be written first to
  // obtain its digest.
  Path tempLayerFile = Files.createTempFile(cache.getCacheDirectory(), null, null);
  // TODO: Find a way to do this with java.nio.file
  tempLayerFile.toFile().deleteOnExit();

  // Writes the UnwrittenLayer layer BLOB to a file to convert into a CachedLayer.
  try (CountingDigestOutputStream compressedDigestOutputStream =
      new CountingDigestOutputStream(
          new BufferedOutputStream(Files.newOutputStream(tempLayerFile)))) {
    // Writes the layer with GZIP compression. The original bytes are captured as the layer's
    // diff ID and the bytes outputted from the GZIP compression are captured as the layer's
    // content descriptor.
    GZIPOutputStream compressorStream = new GZIPOutputStream(compressedDigestOutputStream);
    DescriptorDigest diffId = layer.getBlob().writeTo(compressorStream).getDigest();

    // The GZIPOutputStream must be closed in order to write out the remaining compressed data.
    compressorStream.close();
    BlobDescriptor compressedBlobDescriptor = compressedDigestOutputStream.toBlobDescriptor();

    // Renames the temporary layer file to the correct filename.
    Path layerFile =
        CacheFiles.getLayerFile(cache.getCacheDirectory(), compressedBlobDescriptor.getDigest());
    // TODO: Should probably check for existence of target file and whether or not it's the same.
    try {
      Files.move(tempLayerFile, layerFile);

    } catch (IOException ex) {
      throw new IOException(
          "Could not rename layer "
              + compressedBlobDescriptor.getDigest().getHash()
              + " to "
              + layerFile,
          ex);
    }

    return new CachedLayer(layerFile, compressedBlobDescriptor, diffId);
  }
}
 
Example 16
Project: joal   File: TorrentFileProvider.java   View Source Code Vote up 5 votes
void moveToArchiveFolder(final File torrentFile) {
    if (!torrentFile.exists()) {
        return;
    }
    this.onFileDelete(torrentFile);

    try {
        Files.deleteIfExists(archiveFolder.resolve(torrentFile.getName()));
        Files.move(torrentFile.toPath(), archiveFolder.resolve(torrentFile.getName()));
        logger.info("Successfully moved file: {} to archive folder", torrentFile.getAbsolutePath());
    } catch (final IOException e) {
        logger.warn("Failed to archive file: {}, the file won't be used anymore for the current session, but it remains on the folder.", e);
    }
}
 
Example 17
Project: personium-core   File: CellSnapshotDavCmpFsImpl.java   View Source Code Vote up 5 votes
/**
 * {@inheritDoc}
 * <p>
 * Snapshot file is not encrypted.
 */
@Override
protected ResponseBuilder doPutForUpdate(String contentType, InputStream inputStream, String etag) {
    // Load file info
    this.load();

    // クリティカルなタイミング(ロック~ロードまでの間)でWebDavの管理データが削除された場合の対応
    // WebDavの管理データがこの時点で存在しない場合は404エラーとする
    if (!this.exists()) {
        throw getNotFoundException().params(getUrl());
    }

    // 指定etagがあり、かつそれが*ではなく内部データから導出されるものと異なるときはエラー
    if (etag != null && !"*".equals(etag) && !matchesETag(etag)) {
        throw PersoniumCoreException.Dav.ETAG_NOT_MATCH;
    }

    try {
        // Update Content
        BufferedInputStream bufferedInput = new BufferedInputStream(inputStream);
        File tmpFile = new File(getTempContentFilePath());
        File contentFile = new File(getContentFilePath());
        Files.copy(bufferedInput, tmpFile.toPath());
        Files.delete(contentFile.toPath());
        Files.move(tmpFile.toPath(), contentFile.toPath());
        long writtenBytes = contentFile.length();
        String encryptionType = DataCryptor.ENCRYPTION_TYPE_NONE;

        // Update Metadata
        this.metaFile.setUpdated(new Date().getTime());
        this.metaFile.setContentType(contentType);
        this.metaFile.setContentLength(writtenBytes);
        this.metaFile.setEncryptionType(encryptionType);
        this.metaFile.save();
    } catch (IOException ex) {
        throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND.reason(ex);
    }
    return javax.ws.rs.core.Response.ok().status(HttpStatus.SC_NO_CONTENT).header(HttpHeaders.ETAG, getEtag());
}
 
Example 18
Project: loom-installer   File: LoomInstaller.java   View Source Code Vote up 5 votes
private static void downloadZip(final URL url, final Path target) throws IOException {
    System.out.println("Downloading Loom Library from " + url + " ...");

    final Path parent = target.getParent();

    if (parent == null) {
        throw new IllegalStateException();
    }

    final Path tmpFile = Files.createTempFile(parent, null, null);

    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    try {
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IllegalStateException("Connecting " + url + " resulted in "
                + conn.getHeaderField(0));
        }

        final long totalSize = conn.getContentLengthLong();

        try (final InputStream inputStream = conn.getInputStream();
             final OutputStream out = Files.newOutputStream(tmpFile,
                 StandardOpenOption.APPEND)) {
            copy(inputStream, out, totalSize);
        }
    } finally {
        conn.disconnect();
    }

    if (Files.notExists(target)) {
        Files.move(tmpFile, target, StandardCopyOption.ATOMIC_MOVE);
    }
}
 
Example 19
Project: mo-vnfcp   File: TranslateTopologyToViterbiFormat.java   View Source Code Vote up 4 votes
public static void runViterbiOnFolder(String baseFolder) throws Exception {
    File f = new File(baseFolder);
    String pathToExec = "/home/alex/w/misc/ma/reference-implementation/middlebox-placement/clean/middleman";

    int n = 0;
    File[] files = f.listFiles();
    for (File f2 : files) {
        if (f2.isDirectory()) {
            File[] files2 = f2.listFiles();
            int i = 0;
            for (File f3 : files2) {
                if (f3.isDirectory()) {
                    File topoFile = f3.toPath().resolve("topology-fixed-viterbi").toFile();
                    File vnfFile = f3.toPath().resolve("vnfs-fixed-viterbi").toFile();
                    File reqFile = f3.toPath().resolve("requests-fixed-viterbi").toFile();
                    String exec = pathToExec+" --per_core_cost=0.01 --per_bit_transit_cost=3.626543209876543e-7 --topology_file="+topoFile.getAbsolutePath()+" --middlebox_spec_file="+vnfFile.getAbsolutePath()+" --traffic_request_file="+reqFile.getAbsolutePath()+" --max_time=1440 --algorithm=viterbi";
                    System.out.println("    - Executing " + exec);
                    Process proc = Runtime.getRuntime().exec(exec);

                    proc.waitFor();
                    if (!new File("log.sequences").exists()) {
                        throw new RuntimeException("Result file log.sequences not found");
                    }

                    Path moveFrom = Paths.get("log.sequences");
                    Path moveTo = Paths.get(f3.getAbsolutePath() + "/log.sequences");
                    Files.move(moveFrom, moveTo, StandardCopyOption.REPLACE_EXISTING);

                    String input_topology = f3.toPath().resolve("topology-fixed-psa").toAbsolutePath().toString();
                    String input_vnfs = f3.toPath().resolve("vnfs-fixed-psa").toAbsolutePath().toString();
                    String input_requests = f3.toPath().resolve("requests-fixed-psa").toAbsolutePath().toString();
                    String input_viterbi = moveTo.toString();

                    NetworkGraph ng = TopologyFileReader.readFromFile(input_topology);
                    VnfLib vnfLib = VnfLibReader.readFromFile(input_vnfs);
                    TrafficRequest[] reqs = TrafficRequestsReader.readFromFile(input_requests, ng, vnfLib);

                    Solution s = ViterbiSolutionReader.readFromCsv(ng, reqs, input_viterbi);
                    String[] csv = s.toStringCsv();
                    BufferedWriter w = Files.newBufferedWriter(Paths.get(f3.getAbsolutePath() + "/pareto_frontier_viterbi"));
                    w.write(csv[0] + "\n");
                    w.write(csv[1] + "\n");
                    w.close();

                    System.out.println("  [" + (++i+"/"+files2.length) + "] Problem number " + f3.getName() + " done.");
                }
            }
            System.out.println("[" + (++n+"/"+files.length) + "] Folder " + f2.getName() + " done.");
        }
    }
}
 
Example 20
Project: openjdk-jdk10   File: ToolBox.java   View Source Code Vote up 3 votes
/**
 * 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);
}