Chapter XVII file
In Java7 in on the action file introduces huge improvements. These new elements are placed in java.nio.file
the package below, in the past it usually nio
is n
understood as new
that is the new io, should now be treated as non-blocking
a non-blocking io (io is the input / output I / O).
File operations two basic components:
- File or directory path;
- File itself.
File and directory paths
Paths
An Path
object represents a file or directory path, abstract a cross-operating system (OS) and a file system, aimed at constructing a path without paying attention to the underlying operating system, the code can be run on different operating without modification of on the system. java.nio.file.Paths
Overload class contains a method static get()
, which accepts a series of Strings string or a Uniform Resource Identifier (URI) as an argument, and returns a conversion Path
object.
Partial fragment selected path
public class PartsOfPaths {
public static void main(String[] args) {
System.out.println(System.getProperty("os.name"));
Path p = Paths.get("PartsOfPaths.java").toAbsolutePath();
for (int i = 0; i < p.getNameCount(); i++)
System.out.println(p.getName(i));
System.out.println("ends with '.java': " + p.endsWith(".java"));
for (Path pp : p) {
System.out.print(pp + ": ");
System.out.print(p.startsWith(pp) + " : ");
System.out.println(p.endsWith(pp));
}
System.out.println("Starts with " + p.getRoot() + " " + p.startsWith(p.getRoot()));
}
}
You can getName()
be indexed Path
each part until it reaches the upper limit getNameCount()
. Path
Also inherited the Iterable
interface, we can traverse through enhanced for loop. Please note that even if the path to ending .java, using endsWith()
also the method returns false . This is because endsWith()
the comparison is part of the entire path, the file will not contain a suffix path. By using startsWith()
and endsWith()
can be completed traverse path. But we can see that traverse the Path object does not contain the root path, only the use of startsWith()
return will detect when the root path to true .
Path Analysis
Files
The method includes a full range of tools used to obtain Path
relevant information.
Paths increase or decrease modification
public class AddAndSubtractPaths {
static Path base = Paths.get("..", "..", "..").toAbsolutePath().normalize();
static void show(int id, Path result) {
if (result.isAbsolute())
System.out.println("(" + id + ")r " + base.relativize(result));
else
System.out.println("(" + id + ") " + result);
try {
System.out.println("RealPath: " + result.toRealPath());
} catch (IOException e) {
System.out.println(e);
}
}
public static void main(String[] args) {
System.out.println(System.getProperty("os.name"));
System.out.println(base);
Path p = Paths.get("src","files","AddAndSubtractPaths.java").toAbsolutePath();
show(1, p);
Path convoluted = p.getParent().getParent().resolve("strings").resolve("..")
.resolve(p.getParent().getFileName());
show(2, convoluted);
show(3, convoluted.normalize());
Path p2 = Paths.get("..", "..");
show(4, p2);
show(5, p2.normalize());
show(6, p2.toAbsolutePath().normalize());
Path p3 = Paths.get(".").toAbsolutePath();
Path p4 = p3.resolve(p2);
show(7, p4);
show(8, p4.normalize());
Path p5 = Paths.get("").toAbsolutePath();
show(9, p5);
show(10, p5.resolveSibling("strings"));
show(11, Paths.get("nonexistent"));
}
}
table of Contents
Delete a file or directory:
public class RmDir {
public static void rmdir(Path dir) throws IOException {
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
}
File system
Use FileSystems
tools to obtain a "default" file system. "
public class FileSystemDemo {
static void show(String id, Object o) {
System.out.println(id + ": " + o);
}
public static void main(String[] args) {
System.out.println(System.getProperty("os.name"));
FileSystem fsys = FileSystems.getDefault();
for (FileStore fs : fsys.getFileStores())
show("File Store", fs);
for (Path rd : fsys.getRootDirectories())
show("Root Directory", rd);
show("Separator", fsys.getSeparator());
show("UserPrincipalLookupService", fsys.getUserPrincipalLookupService());
show("isOpen", fsys.isOpen());
show("isReadOnly", fsys.isReadOnly());
show("FileSystemProvider", fsys.provider());
show("File Attribute Views", fsys.supportedFileAttributeViews());
}
}
Path monitor
By WatchService
responding to changes in the directory you can set up a process.
File search
By FileSystem
calling on the object getPathMatcher()
to get a PathMatcher
, then pass mode you are interested in. Mode has two options: glob
and regex
.
File read and write
Files.readAllLines()
Once read the entire file (Therefore, the "small" file is necessary), to produce a List<String>
. There is a readAllLines()
heavy-duty version, which contains a Charset
parameter to Unicode encoded file is stored.
Files.write()
Overload is written to byte
the array, or any Iterabl
e object (which is also Charset option).
Files.lines()
Easily convert the file to the line Stream
.