Skip to main content

Manipulating Files in Java 7

From 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 perms
    = PosixFilePermissions.fromString("rw-rw-rw-");
FileAttribute> attr
    = PosixFilePermissions.asFileAttribute(perms);
Files.createFile(target, attr);
The java.nio.file.attribute package contains a list of provided FilePermissionclasses. 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 umaskrestrictions 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) andATOMIC_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 theFiles.move(Path source, Path target, CopyOptions...) method (note the use ofvarargs).
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!

Comments

Popular posts from this blog

How to install JSVC on Linux WidenHome Log | WidenHome Log

How to install JSVC on Linux WidenHome Log | WidenHome Log In our team, we have a lot of Java standalone applications which should be run as daemon on Unix/Linux system, and we found JSVC is the best choice for us to wrap Java programs to daemons. This article records the steps on how to install JSVC executable on Linux, which is our stage/prod environment. Download JSVC source package First of all, we need to download JSVC source package from this URL: http://commons.apache.org/daemon/download_daemon.cgi , for example, I downloaded commons-daemon-1.0.5-src.tar.gz file. Or, download it via wget: wget -c http://apache.etoak.com/commons/daemon/source/commons-daemon-1.0.5-src.tar.gz Build JSVC executable Unzip the source package and build JSVC executable. chmod 755 commons-daemon-1.0.5-src.tar.gz tar zxvf commons-daemon-1.0.5-src.tar.gz cd commons-daemon-1.0.5-src/src/native/unix Before building the JSVC executable, please make sure you have set JAVA_HOME variable correctly. And make sur...

Java中的Serializable浅谈

from  http://www.cnblogs.com/vicenteforever/articles/1471775.html 对象的串行化(Serialization) 一、串行化的概念和目的 1.什么是串行化             对象的寿命通常随着生成该对象的程序的终止而终止。有时候,可能需要将对象的状态保存下来,在需要时再将对象恢复。我们把对象的这种能记录自己的状态以便将来再生的能力。叫作对象的持续性(persistence)。对象通过写出描述自己状态的数值来记录自己 ,这个过程叫对象的串行化(Serialization) 。串行化的主要任务是写出对象实例变量的数值。如果交量是另一对象的引用,则引用的对象也要串行化。这个过程是递归的,串行化可能要涉及一个复杂树结构的单行化,包括原有对象、对象的对象、对象的对象的对象等等。对象所有权的层次结构称为图表(graph)。 2.串行化的目的             Java对象的单行化的目标是为Java的运行环境提供一组特性,如下所示: 1)       尽量保持对象串行化的简单扼要 ,但要提供一种途径使其可根据开发者的要求进行扩展或定制。 2)       串行化机制应严格遵守Java的对象模型 。对象的串行化状态中应该存有所有的关于种类的安全特性的信息。 3)       对象的串行化机制应支持Java的对象持续性。 4)       对象的串行化机制应有足够的 可扩展能力以支持对象的远程方法调用(RMI)。 5)       对象串行化应允许对象定义自身 的格式即其自身的数据流表示形式,可外部化接口来完成这项功能。 什么情况下需要序列化 a)当...