About Martijn Verburg

Martijn (aka "The Diabolical Developer") is the co-founder and CTO of jClarity. He's a London Java Community leader, founder of the "Adopt a JSR" and "Adopt OpenJDK" programmes, a speaker at major conferences and the co-author of the Well-Grounded Java Developer.

Manipulating Files in Java 7

The following is a modified snippet from a draft of The Well-Grounded Java Developer. It gives you a quick taster of how much easier it is to manipulate files in Java 7 than in previous versions. By using the new Files class and its many utility methods, you can perform the following operations on files with only a single line of code:

  • Create
  • Delete
  • Copy
  • Move/Rename

TIP A quick note on Path. This post assumes you have some passing familiarity with the new Java 7 Path class, if not here’s a quick introduction! Path is the logical abstraction of a location on the file system, e.g. c:\” is a Path as is “../foobar.txt”

Let’s start by looking at the creation and deletion of files.

Creating and Deleting files

By using the simple helper methods in the Files class you can create files and delete them easily as well.

TIP If you are running the code snippets in this section, replace the actual paths with ones that match your file system!

The following code snippet shows basic file creation, using the Files.createFile(Path target) method.

Path target = Paths.get("D:\\Backup\\MyStuff.txt");
Path file = Files.createFile(target);

More often than not you want to specify some file attributes on that file for security purposes as well as knowing whether the file is being created for the purpose of reading and/or writing and/or executing. As this is file system dependent, you need to utilise a file system specific file permissions class and its helper.

For example, PosixFilePermission and PosixFilePermissions for a POSIX compliant file system. An example of setting read/write for the owner-group-all in a POSIX file system is as follows.

Path target = Paths.get("D:\\Backup\\MyStuff.txt");
Set<PosixFilePermission> perms
= PosixFilePermissions.fromString("rw-rw-rw-");
FileAttribute<Set<PosixFilePermission>> attr
= PosixFilePermissions.asFileAttribute(perms);
Files.createFile(target, attr);

The java.nio.file.attribute package contains a list of provided FilePermission classes. File attribute support is also covered in further detail in chapter 2 of The Well-Grounded Java Developer.

WARNING When creating files with specific permissions, do be aware of any umask restrictions or restrictive permissions that the parent directory of that file is enforcing. For example, you may find that even though you specify rw-rw-rw for your new file, it is actually created as rw-r–r– due to these restrictions.

Deleting a file is a bit simpler and is performed by the simple Files.delete(Path) method.

Path target = Paths.get("D:\\Backup\\MyStuff.txt");

Next up a quick overview on copying and moving files in a file system.

Copying and Moving files

By using the simple helper methods in the Files class you can perform your copy and move operations with ease. The following code snippet showcases a basic copy, using the Files.copy(Path source, Path target) method.

Path source = Paths.get("C:\\My Documents\\Stuff.txt");
Path target = Paths.get("D:\\Backup\\MyStuff.txt");
Files.copy(source, target);

More often than not you want to specify some options with the copy operation. In Java 7 you can use the StandardCopyOption enum to specify these options. The next example uses an overwrite (that is, replace existing) option.

import static java.nio.file.StandardCopyOption.*;

Path source = Paths.get("C:\\My Documents\\Stuff.txt");
Path target = Paths.get("D:\\Backup\\MyStuff.txt");
Files.copy(source, target, REPLACE_EXISTING);

Other copy options include COPY_ATTRIBUTES (copies over the file attributes) and ATOMIC_MOVE (ensures that both sides of a move operation succeed or the operation gets rolled back).The move operation is very similar to the copy operation and is executed using the atomic Files.move(Path source, Path target) method.

Again you typically want some copy options to go with that move, so you can use the Files.move(Path source, Path target, CopyOptions…) method (note the use of varargs).

In this case we want to keep the attributes of the source file when we move it as well as overwriting the target file (if it exists).

import static java.nio.file.StandardCopyOption.*;

Path source = Paths.get("C:\\My Documents\\Stuff.txt");
Path target = Paths.get("D:\\Backup\\MyStuff.txt");
Files.move(source, target, REPLACE_EXISTING, COPY_ATTRIBUTES);

As you can see, the new NIO.2 API for file manipulation is simple to use, we hope you enjoyed this little taster!

Happy Coding! Do not forget to share!

References :

Related Articles:

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

Leave a Reply

5 − = four

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books