Manipulating Files in Java 7

7 Comments

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");
Files.delete(target);

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 and our apologies for the long wait between posts!

Did you like this? Share it:

Ben and Martijn are interviewed at Javaworld

No Comments

The interview is live here

Did you like this? Share it:

Modularity is Hard. Let’s do a Jigsaw.

12 Comments

Don’t forget: The 50% discount on the Early Access edition of our book expires tomorrow!

(Before we get underway, I want to make the point that all of this is based on my current understanding of the positions of both the OSGi folk and the current plans for Jigsaw. I’m not an expert in either, so there may well be egregious lies in this post. Informed comment from people who are an expert in either technology would be very welcome.)

Technologists don’t possess crystal balls. Early releases of technology platforms often have problems in them that are not ironed out (or even discovered) until much later.

One example of this is the Java platform’s lack of generalised modularisation and dependency management capability in the core. Sure, there are jar files, and as a basic means of shipping around units of functionality which are larger than a class, they’re OK.

However, when dealing with larger systems, the model of “just ship around a bunch of jars and manually manage the dependencies” starts to break down. What’s needed is a way to automatically manage the dependencies between functional units, via some metadata which is shipped within each unit.

This is where systems like Apache Ivy and Maven come from – they run outside of the core platform and automatically manage a repository of jar files. Build and runtime dependencies are then much easier to manage – all the jars are in one place. However, note that the platform doesn’t provide any support for these platforms out of the box – a classpath still has to be managed for start scripts, etc.

What would be better is if the platform provided for automatic management of dependencies in the core. Both of the mostly widely used systems broadly agree about which relationships between functional units need to be expressible, so there’s no major disagreement about what needs to be expressed.

The simplest cases are that a unit needs to be able to say that it requires:

  • a particular version of a certain other unit
  • a particular version or anything higher
  • any version within a given range.

Dependencies should also be able to be marked as mandatory or optional, and different isolated contexts within the same JVM should be able to have different, incompatible versions of the same unit.

This much is basically agreed upon. Where the different viewpoints diverge is over what constitutes a functional unit, and at what stage of platform startup the dependency management and modularity functionality should kick in. The two big schools of thought are the OSGi view and the Project Jigsaw view.

OSGi

  1. Unit of sharing should be the package. This reduces conceptual burden on developers to learn a new model and is simpler.
  2. Dependency management should start once the platform is fully bootstrapped. This allows the benefits to be brought to any compliant installation, and doesn’t require changes to the core platform.

Project Jigsaw

  1. Unit of sharing should be a new concept – the module. This is “larger” than a package, and packages can also be split between modules.
  2. Changes should be made to the core, and the platform itself should be aware of module dependencies as early as possible. This is more work, and requires more co-ordination between implementations, but has potentially has big wins (quicker startup time, smaller footprint).

Which should you choose for your application? Well, Jigsaw is still being developed, and won’t land as part of Java 7 – it’s targeting Java 8. OSGi is a production technology, used in a surprising number of places (if you’ve ever used Eclipse, you’ve used OSGi technology, you just probably weren’t aware of it). However, it is still maturing – there are gaps around tooling, and there are gaps in the standard which has led to different approaches between vendors, with regard to e.g. bundle deployment.

If you want to learn a new technology, then Jigsaw is still very new, and a moving target, whereas OSGi is here today. On the other hand, unless you have a clear benefit from deploying something like this today, it may be preferable to live with the pain of Ivy/Maven and wait for the space to mature.

Finally, as a modest proposal, let’s talk about deprecation.

Java has always been bad at deprecation. We’ve known that Thread#stop and friends were the wrong thing to do for a very long time, but they’re still there, hanging on as deprecated methods. In the current setup it seems impossible to do anything to remove them. With a wide-ranging modularity solution, such as Jigsaw, in place – could we produce a release of a core module which removed the likes of Thread#stop and Object#finalize ?

Did you like this? Share it:

The Early Access Program has been updated!

No Comments

The 2nd release for the book has reached the MEAP (Manning Early Access Program).

This means that you can pre-order it, and get access to the chapters as we write them. There’s now an updated ToC, an updated Chapter 1 (Introducing Java 7) is available for free, with Chapters 2 and 3 (and now Chapter 4 – concurrency!!) available to people who pre-order.

Until the 3rd of March you can use our discount code wellgrndjava50 and get 50% off!

To download chapter 1, or pre-order, see our page on Manning’s website.

Did you like this? Share it:

We have a Facebook Page!

No Comments

Yes, for all of you crackbookI mean Facebook users, we now have our very own page for “The Well-Grounded Java Developer”. Please do visit us there and tell your colleagues!

Did you like this? Share it:

50% Discount Promo Code For Our MEAP

2 Comments

The lovely people at Manning have provided a discount code, so that readers of our blog can get a whopping 50% off our MEAP.

To use it, just go to our page on Manning’s website http://www.manning.com/evans/ and then enter the code: wellgrndjava50 as you go through checkout, to get the MEAP (and a printed book if you want one, when it’s released) at a 50% discount.

There’ll be new content (including Chapter 4) for the MEAP very soon, so this is an excellent time to get your copy.

Did you like this? Share it:

The Early Access Program Has Begun!

No Comments

Sorry if we’ve been a bit quiet recently – we’ve been busy getting our chapters ready for our first review.

But the big news is that our book has reached MEAP (Manning Early Access Program).

This means that you can pre-order it, and get access to the chapters as we write them. Right now, chapter 1 (Introducing Java 7) is available free, with chapters 2 and 3 available to people who pre-order.

To download chapter 1, or pre-order, see our page on Manning’s website.

Did you like this? Share it:

Book Cover!

No Comments

Book Cover!

Did you like this? Share it: