Nov 092013
 
Article Java

In this post you can find some code examples written in the java language to perform common file operations.

Renaming a file

The base class java.io.File implements a renameTo method that can be used to rename a file.

For instance, renaming a file “data.txt” to “data.csv” can be done with the following sentences:

As we can see, the renameTo() method just returns true if the operation has been successfully carried out, and false otherwise.

But there are several reasons that could cause a failure in the renaming operation: The source file does not exist, the user has not enough privileges to rename the file, there exists a file with the same destination name, etc…

To determine the cause of the error, some sentences can be added before the call to renameTo. For instance, to check that the source file exists and the destination file does not exist:

Moving a file to a different directory

The renameTo() method in class java.io.File can also be used to move a file to another directory, if the filename of the destination file includes a path (absolute or relative) to the new directory.

But renameTo() fails is the destination directory is in a different filesystem or disk than the source file.

In Java 6, this issue can be solved by making firs a copy of the file to the destination directory (as explained below), and then removing the original with a call to the delete() method in java.io.File.

Copy a file in Java 6

As already mentioned, there is no “copy()” method in the base libraries of Java 6.

But a function to perform the copy can be easily written using class java.nio.channels.FileChannel:

Copy a file in Java 7

In Java 7, there is a class java.nio.file.Files that implements a set of static methods to perform most common file handling operations. Among them there is a copy() method that can be used to copy a file, even if the destination directory is in a different filesystem.

The copy() method accepts an argument of class CopyOptions, that can be used to specify:

If the destination file is to be overwritten in case it exists.

If attributes (including permissions) or the source file are to be replicated in the destination file:

References:

Index of posts related to Java programming

 Posted by at 11:58 am

 Leave a Reply

(required)

(required)