Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

chapter 9 Java File I/O (NIO.2)

You use the readAttribute() method along with BasicFileAttributes to retrieve basic file properties. Similarly, you can retrieve attributes associated with a file in a DOS or UNIX environment using DosFileAttributes and PosixFileAttributes, respectively.

Copying a File

Now let’s try copying a file/directory from one location to another location. This task is easy to accomplish: just call Files.copy() to copy the file from source to target. Here is the signature of this method:

Path copy(Path source, Path target, CopyOption. . . options)

Listing 9-9 uses this method to write a simple file copy program.

Listing 9-9.  FileCopy.java

import java.io.IOException; import java.nio.file.*;

public class FileCopy {

public static void main(String[] args) { if(args.length != 2){

System.out.println("usage: FileCopy <source-path> <destination-path>"); System.exit(1);

}

Path pathSource = Paths.get(args[0]); Path pathDestination = Paths.get(args[1]); try {

Files.copy(pathSource, pathDestination); System.out.println("Source file copied successfully");

} catch (IOException e) { e.printStackTrace();

}

}

}

Let’s execute it and see whether it works.

D:\> java FileCopy FileCopy.java Backup.java Source file copied successfully

Yes, it’s working. Let’s try running it again with same arguments.

D:\OCPJP7\programs\NIO2\src>java FileCopy FileCopy.java Backup.java java.nio.file.FileAlreadyExistsException: Backup.java

at sun.nio.fs.WindowsFileCopy.copy(Unknown Source) [. . .stack trace elided. . .]

Oops! What happened? When you tried copying the file for the second time, you got a FileAlreadyExistsException since the destination file already exists. So, what if you want to overwrite the existing

264

chapter 9 Java File I/O (NIO.2)

file? The solution: you need to tell the copy() method that you would like to overwrite an existing file. In Listing 9-9, change the copy() method as follows:

Files.copy(pathSource, pathDestination, StandardCopyOption.REPLACE_EXISTING);

In this change, you are specifying an additional argument (since the copy() method supports variable arguments) to tell the method that you want to overwrite a file if it already exists. So, let’s run this program and see whether it works.

D:\>java FileCopy FileCopy.java Backup.java Source file copied successfully

D:\>java FileCopy FileCopy.java Backup.java Source file copied successfully

Yes, it works. Now, try to copy a file to a new directory.

D:\OCPJP7\programs\NIO2\src>java FileCopy FileCopy.java bak\Backup.java java.nio.file.NoSuchFileException: FileCopy.java -> bak\Backup.java

[. . .stack trace elided . . .]

Well, here you tried to copy a file to back directory that does not exist. For this, you got the NoSuchFileException. Note that not just the given directory but all intermediate directories in a path must exist for the copy() method to succeed.

All the directories (except the last one if you are copying a directory) in the specified path must exist to avoid NoSuchFileException.

What if you try copying a directory? It will work, but remember that it will only copy the top-level directory, not the not the files/directories contained within that directory.

If you copy a directory using the copy() method, it will not copy the files/directories contained in the source directory; you need to explicitly copy them to the destination folder.

You will revisit this topic later in this chapter when you implement a copy program that can copy a directory into another directory along with the contained files/directories.

Moving a File

Moving a file is quite similar to copying a file; for this purpose, you can use the Files.move() method. The signature of this method is

Path move(Path source, Path target, CopyOption. . . options)

265

chapter 9 Java File I/O (NIO.2)

Listing 9-10 contains a small program that uses this method.

Listing 9-10.  FileMove.java

import java.io.IOException; import java.nio.file.*;

public class FileMove {

public static void main(String[] args) { if(args.length != 2){

System.out.println("usage: FileMove <source-path> <destination-path>"); System.exit(−1);

}

Path pathSource = Paths.get(args[0]); Path pathDestination = Paths.get(args[1]); try {

Files.move(pathSource, pathDestination, StandardCopyOption.REPLACE_EXISTING); System.out.println("Source file moved successfully");

} catch (IOException e) { e.printStackTrace();

}

}

}

This basic implementation works fine. However, here are some observations peculiar to the move() method:

As is the case with the copy() method, the move() method also does not overwrite the existing destination file unless you specify it to do so using REPLACE_EXISTING.

If you move a symbolic link, the link itself will be moved, not the target file of the link. It is important to note that in the case of the copy() method, if you specify a symbolic link, the target of the link is copied, not the link itself.

A non-empty directory can be moved if moving the directory does not require moving the containing files/directories. For instance, moving a directory from one physical drive to another might be unsuccessful (an IOException will be thrown). If moving a directory operation is successful, then all the contained files/directories will also be moved.

You can specify a move() operation as an atomic operation using the ATOMIC_MOVE copy option. If move() is performed as a non-atomic operation and it fails in between, the state of both files is unknown and undefined.

Deleting a File

The Files class provides a delete() method to delete a file/directory/symbolic link. Listing 9-11 contains a simple program to delete a specified file.

Listing 9-11.  FileDelete.java

import java.io.IOException; import java.nio.file.*;

public class FileDelete {

public static void main(String[] args) {

266

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]