File moving in java

Moving a File or Directory

You can move a file or directory by using the move(Path, Path, CopyOption. ) method. The move fails if the target file exists, unless the REPLACE_EXISTING option is specified.

Empty directories can be moved. If the directory is not empty, the move is allowed when the directory can be moved without moving the contents of that directory. On UNIX systems, moving a directory within the same partition generally consists of renaming the directory. In that situation, this method works even when the directory contains files.

This method takes a varargs argument – the following StandardCopyOption enums are supported:

  • REPLACE_EXISTING – Performs the move even when the target file already exists. If the target is a symbolic link, the symbolic link is replaced but what it points to is not affected.
  • ATOMIC_MOVE – Performs the move as an atomic file operation. If the file system does not support an atomic move, an exception is thrown. With an ATOMIC_MOVE you can move a file into a directory and be guaranteed that any process watching the directory accesses a complete file.

The following shows how to use the move method:

import static java.nio.file.StandardCopyOption.*; . Files.move(source, target, REPLACE_EXISTING);

Though you can implement the move method on a single directory as shown, the method is most often used with the file tree recursion mechanism. For more information, see Walking the File Tree.

Previous page: Copying a File or Directory
Next page: Managing Metadata (File and File Store Attributes)

Источник

Java – Rename or Move a File

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Читайте также:  Show pid in php

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Читайте также:  Php include output to string

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this quick tutorial, we’re going to look at renaming / moving a File in Java.

We’ll first look into using the Files and Path classes from NIO, then the Java File class, Google Guava, and finally the Apache Commons IO library.

This article is part of the “Java – Back to Basic” series here on Baeldung.

Further reading:

How to Copy a File with Java

Introduction to the Java NIO2 File API

File Size in Java

2. Setup

In the examples, we’ll use the following setup, which consists of 2 constants for the source and destination file name and a clean-up step to be able to run the tests multiple times:

private final String FILE_TO_MOVE = "src/test/resources/originalFileToMove.txt"; private final String TARGET_FILE = "src/test/resources/targetFileToMove.txt"; @BeforeEach public void createFileToMove() throws IOException < File fileToMove = new File(FILE_TO_MOVE); fileToMove.createNewFile(); >@AfterEach public void cleanUpFiles()

3. Using the NIO Paths and Files Classes

Let’s start by using the Files.move() method from the Java NIO package:

@Test public void givenUsingNio_whenMovingFile_thenCorrect() throws IOException

In JDK7 the NIO package was significantly updated, and the Path class added. This provides methods for convenient manipulation of File System artifacts.

Note that both the file and the target directory should exist.

4. Using the File Class

Let’s now look at how we can do the same using the File.renameTo() method:

@Test public void givenUsingFileClass_whenMovingFile_thenCorrect() throws IOException < File fileToMove = new File(FILE_TO_MOVE); boolean isMoved = fileToMove.renameTo(new File(TARGET_FILE)); if (!isMoved) < throw new FileSystemException(TARGET_FILE); >>

In this example, the file to be moved does exist, as well as the target directory.

Читайте также:  Питон бесконечный цикл while

Note that renameTo() only throws two types of exceptions:

  • SecurityException – if a security manager denies writing access to either the source or to the destination
  • NullPointerException – in case the parameter target is null

If the target does not exist in a file system – no exception will be thrown – and you will have to check the returned success flag of the method.

5. Using Guava

Next – let’s take a look at the Guava solution, which provides a convenient Files.move() method:

@Test public void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException

Again, in this example, the file to be moved and the target directory need to exist.

6. With Commons IO

Finally, let’s take a look at a solution with Apache Commons IO – probably the simplest one:

@Test public void givenUsingApache_whenMovingFile_thenCorrect() throws IOException

This one line will, of course, allow both moving or renaming, depending on if the target directory is the same or not.

Alternatively – here’s a solution for moving specifically, also enabling us to automatically create the destination directory if it doesn’t already exist:

@Test public void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException < FileUtils.moveFileToDirectory( FileUtils.getFile("src/test/resources/fileToMove.txt"), FileUtils.getFile("src/main/resources/"), true); >

6. Conclusion

In this article, we looked at different solutions for moving a file in Java. We focused on renaming in these code snippets, but moving is, of course, the same, only the target directory needs to be different.

The code for the examples is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью