Demo.java revision 4123
0N/A/*
3909N/A * Copyright (c) 2010 Oracle and/or its affiliates. All rights reserved.
0N/A *
0N/A * Redistribution and use in source and binary forms, with or without
0N/A * modification, are permitted provided that the following conditions
0N/A * are met:
2362N/A *
0N/A * - Redistributions of source code must retain the above copyright
2362N/A * notice, this list of conditions and the following disclaimer.
0N/A *
0N/A * - Redistributions in binary form must reproduce the above copyright
0N/A * notice, this list of conditions and the following disclaimer in the
0N/A * documentation and/or other materials provided with the distribution.
0N/A *
0N/A * - Neither the name of Oracle nor the names of its
0N/A * contributors may be used to endorse or promote products derived
0N/A * from this software without specific prior written permission.
0N/A *
0N/A * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
0N/A * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
2362N/A * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2362N/A * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
2362N/A * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
0N/A * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
0N/A * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
0N/A * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
0N/A * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
0N/A * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
0N/A * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0N/A */
0N/A
2965N/Aimport java.io.*;
0N/Aimport java.nio.*;
0N/Aimport java.nio.channels.*;
0N/Aimport java.nio.file.*;
0N/Aimport java.nio.file.spi.*;
0N/Aimport java.nio.file.attribute.*;
0N/Aimport java.net.*;
0N/Aimport java.text.DateFormat;
0N/Aimport java.text.SimpleDateFormat;
0N/Aimport java.util.*;
0N/A
0N/Aimport static java.nio.file.StandardOpenOption.*;
0N/Aimport static java.nio.file.StandardCopyOption.*;
0N/A/*
0N/A * ZipFileSystem usage demo
0N/A *
0N/A * java Demo action ZipfileName [...]
0N/A *
0N/A * @author Xueming Shen
0N/A */
0N/A
0N/Apublic class Demo {
0N/A
0N/A static enum Action {
0N/A rename, // <java Demo rename zipfile src dst>
0N/A // rename entry src to dst inside zipfile
0N/A
0N/A movein, // <java Demo movein zipfile src dst>
3724N/A // move an external src file into zipfile
3724N/A // as entry dst
3724N/A
3724N/A moveout, // <java Demo moveout zipfile src dst>
3724N/A // move a zipfile entry src out to dst
3724N/A
3724N/A copy, // <java Demo copy zipfile src dst>
3724N/A // copy entry src to dst inside zipfile
0N/A
0N/A copyin, // <java Demo copyin zipfile src dst>
0N/A // copy an external src file into zipfile
0N/A // as entry dst
0N/A
0N/A copyin_attrs, // <java Demo copyin_attrs zipfile src dst>
0N/A // copy an external src file into zipfile
0N/A // as entry dst, with attributes (timestamp)
0N/A
0N/A copyout, // <java Demo copyout zipfile src dst>
0N/A // copy zipfile entry src" out to file dst
0N/A
0N/A copyout_attrs, // <java Demo copyout_attrs zipfile src dst>
0N/A
0N/A zzmove, // <java Demo zzmove zfsrc zfdst path>
0N/A // move entry path/dir from zfsrc to zfdst
0N/A
0N/A zzcopy, // <java Demo zzcopy zfsrc zfdst path>
0N/A // copy path from zipfile zfsrc to zipfile
0N/A // zfdst
0N/A
0N/A attrs, // <java Demo attrs zipfile path>
0N/A // printout the attributes of entry path
0N/A
0N/A attrsspace, // <java Demo attrsspace zipfile path>
0N/A // printout the storespace attrs of entry path
0N/A
0N/A setmtime, // <java Demo setmtime zipfile "MM/dd/yy-HH:mm:ss" path...>
0N/A // set the lastModifiedTime of entry path
0N/A
0N/A setatime, // <java Demo setatime zipfile "MM/dd/yy-HH:mm:ss" path...>
0N/A setctime, // <java Demo setctime zipfile "MM/dd/yy-HH:mm:ss" path...>
0N/A
0N/A lsdir, // <java Demo lsdir zipfile dir>
0N/A // list dir's direct child files/dirs
0N/A
0N/A mkdir, // <java Demo mkdir zipfile dir>
0N/A
0N/A mkdirs, // <java Demo mkdirs zipfile dir>
0N/A
0N/A rmdirs, // <java Demo rmdirs zipfile dir>
0N/A
0N/A list, // <java Demo list zipfile [dir]>
0N/A // recursively list all entries of dir
0N/A // via DirectoryStream
0N/A
0N/A tlist, // <java Demo tlist zipfile [dir]>
0N/A // list with buildDirTree=true
0N/A
0N/A vlist, // <java Demo vlist zipfile [dir]>
0N/A // recursively verbose list all entries of
0N/A // dir via DirectoryStream
0N/A
0N/A walk, // <java Demo walk zipfile [dir]>
0N/A // recursively walk all entries of dir
0N/A // via Files.walkFileTree
0N/A
0N/A twalk, // <java Demo twalk zipfile [dir]>
0N/A // walk with buildDirTree=true
0N/A
0N/A extract, // <java Demo extract zipfile file [...]>
0N/A
0N/A update, // <java Demo extract zipfile file [...]>
0N/A
0N/A delete, // <java Demo delete zipfile file [...]>
0N/A
0N/A add, // <java Demo add zipfile file [...]>
0N/A
0N/A create, // <java Demo create zipfile file [...]>
0N/A // create a new zipfile if it doesn't exit
0N/A // and then add the file(s) into it.
0N/A
0N/A attrs2, // <java Demo attrs2 zipfile file [...]>
0N/A // test different ways to print attrs
0N/A
0N/A prof,
0N/A }
0N/A
0N/A public static void main(String[] args) throws Throwable {
0N/A FileSystemProvider provider = getZipFSProvider();
0N/A if (provider == null) {
0N/A System.err.println("ZIP filesystem provider is not installed");
0N/A System.exit(1);
0N/A }
0N/A
0N/A Action action = Action.valueOf(args[0]);
0N/A Map<String, Object> env = env = new HashMap<>();
0N/A if (action == Action.create)
0N/A env.put("create", "true");
0N/A try (FileSystem fs = provider.newFileSystem(Paths.get(args[1]), env)) {
0N/A Path path, src, dst;
0N/A switch (action) {
0N/A case rename:
0N/A src = fs.getPath(args[2]);
0N/A dst = fs.getPath(args[3]);
0N/A Files.move(src, dst);
0N/A break;
0N/A case moveout:
0N/A src = fs.getPath(args[2]);
0N/A dst = Paths.get(args[3]);
0N/A Files.move(src, dst);
0N/A break;
0N/A case movein:
0N/A src = Paths.get(args[2]);
0N/A dst = fs.getPath(args[3]);
0N/A Files.move(src, dst);
0N/A break;
0N/A case copy:
0N/A src = fs.getPath(args[2]);
0N/A dst = fs.getPath(args[3]);
0N/A Files.copy(src, dst);
0N/A break;
0N/A case copyout:
0N/A src = fs.getPath(args[2]);
0N/A dst = Paths.get(args[3]);
0N/A Files.copy(src, dst);
0N/A break;
0N/A case copyin:
0N/A src = Paths.get(args[2]);
0N/A dst = fs.getPath(args[3]);
0N/A Files.copy(src, dst);
0N/A break;
0N/A case copyin_attrs:
0N/A src = Paths.get(args[2]);
0N/A dst = fs.getPath(args[3]);
0N/A Files.copy(src, dst, COPY_ATTRIBUTES);
0N/A break;
0N/A case copyout_attrs:
0N/A src = fs.getPath(args[2]);
0N/A dst = Paths.get(args[3]);
0N/A Files.copy(src, dst, COPY_ATTRIBUTES);
0N/A break;
0N/A case zzmove:
0N/A try (FileSystem fs2 = provider.newFileSystem(Paths.get(args[2]), env)) {
0N/A z2zmove(fs, fs2, args[3]);
0N/A }
0N/A break;
0N/A case zzcopy:
0N/A try (FileSystem fs2 = provider.newFileSystem(Paths.get(args[2]), env)) {
0N/A z2zcopy(fs, fs2, args[3]);
0N/A }
0N/A break;
0N/A case attrs:
0N/A for (int i = 2; i < args.length; i++) {
0N/A path = fs.getPath(args[i]);
0N/A System.out.println(path);
0N/A System.out.println(
0N/A Files.readAttributes(path, BasicFileAttributes.class).toString());
0N/A }
0N/A break;
0N/A case setmtime:
0N/A DateFormat df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");
0N/A Date newDatetime = df.parse(args[2]);
0N/A for (int i = 3; i < args.length; i++) {
0N/A path = fs.getPath(args[i]);
0N/A Files.setAttribute(path, "lastModifiedTime",
0N/A FileTime.fromMillis(newDatetime.getTime()));
0N/A System.out.println(
0N/A Files.readAttributes(path, BasicFileAttributes.class).toString());
0N/A }
0N/A break;
0N/A case setctime:
0N/A df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");
0N/A newDatetime = df.parse(args[2]);
0N/A for (int i = 3; i < args.length; i++) {
0N/A path = fs.getPath(args[i]);
0N/A Files.setAttribute(path, "creationTime",
0N/A FileTime.fromMillis(newDatetime.getTime()));
0N/A System.out.println(
0N/A Files.readAttributes(path, BasicFileAttributes.class).toString());
0N/A }
0N/A break;
0N/A case setatime:
0N/A df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");
0N/A newDatetime = df.parse(args[2]);
0N/A for (int i = 3; i < args.length; i++) {
0N/A path = fs.getPath(args[i]);
0N/A Files.setAttribute(path, "lastAccessTime",
0N/A FileTime.fromMillis(newDatetime.getTime()));
0N/A System.out.println(
0N/A Files.readAttributes(path, BasicFileAttributes.class).toString());
0N/A }
0N/A break;
0N/A case attrsspace:
0N/A path = fs.getPath("/");
0N/A FileStore fstore = Files.getFileStore(path);
0N/A System.out.printf("filestore[%s]%n", fstore.name());
0N/A System.out.printf(" totalSpace: %d%n",
0N/A (Long)fstore.getAttribute("totalSpace"));
0N/A System.out.printf(" usableSpace: %d%n",
0N/A (Long)fstore.getAttribute("usableSpace"));
0N/A System.out.printf(" unallocSpace: %d%n",
0N/A (Long)fstore.getAttribute("unallocatedSpace"));
0N/A break;
0N/A case list:
0N/A case tlist:
0N/A if (args.length < 3)
0N/A list(fs.getPath("/"), false);
0N/A else
0N/A list(fs.getPath(args[2]), false);
0N/A break;
0N/A case vlist:
0N/A if (args.length < 3)
0N/A list(fs.getPath("/"), true);
0N/A else
0N/A list(fs.getPath(args[2]), true);
0N/A break;
0N/A case twalk:
0N/A case walk:
0N/A walk(fs.getPath((args.length > 2)? args[2] : "/"));
0N/A break;
0N/A case extract:
2965N/A if (args.length == 2) {
0N/A extract(fs, "/");
0N/A } else {
0N/A for (int i = 2; i < args.length; i++) {
0N/A extract(fs, args[i]);
0N/A }
0N/A }
0N/A break;
0N/A case delete:
0N/A for (int i = 2; i < args.length; i++)
0N/A Files.delete(fs.getPath(args[i]));
0N/A break;
0N/A case create:
0N/A case add:
0N/A case update:
0N/A for (int i = 2; i < args.length; i++) {
0N/A update(fs, args[i]);
0N/A }
0N/A break;
0N/A case lsdir:
0N/A path = fs.getPath(args[2]);
0N/A final String fStr = (args.length > 3)?args[3]:"";
0N/A try (DirectoryStream<Path> ds = Files.newDirectoryStream(path,
0N/A new DirectoryStream.Filter<Path>() {
0N/A @Override
0N/A public boolean accept(Path path) {
213N/A return path.toString().contains(fStr);
213N/A }
213N/A }))
213N/A {
213N/A for (Path p : ds)
213N/A System.out.println(p);
213N/A }
213N/A break;
213N/A case mkdir:
213N/A Files.createDirectory(fs.getPath(args[2]));
213N/A break;
213N/A case mkdirs:
213N/A mkdirs(fs.getPath(args[2]));
213N/A break;
213N/A case attrs2:
213N/A for (int i = 2; i < args.length; i++) {
213N/A path = fs.getPath(args[i]);
213N/A System.out.printf("%n%s%n", path);
213N/A System.out.println("-------(1)---------");
213N/A System.out.println(
213N/A Files.readAttributes(path, BasicFileAttributes.class).toString());
213N/A System.out.println("-------(2)---------");
213N/A Map<String, Object> map = Files.readAttributes(path, "zip:*");
213N/A for (Map.Entry<String, Object> e : map.entrySet()) {
213N/A System.out.printf(" %s : %s%n", e.getKey(), e.getValue());
213N/A }
0N/A System.out.println("-------(3)---------");
0N/A map = Files.readAttributes(path, "size,lastModifiedTime,isDirectory");
0N/A for (Map.Entry<String, ?> e : map.entrySet()) {
0N/A System.out.printf(" %s : %s%n", e.getKey(), e.getValue());
0N/A }
0N/A }
0N/A break;
0N/A case prof:
0N/A list(fs.getPath("/"), false);
0N/A while (true) {
0N/A Thread.sleep(10000);
0N/A //list(fs.getPath("/"), true);
0N/A System.out.println("sleeping...");
0N/A }
0N/A }
0N/A } catch (Exception x) {
0N/A x.printStackTrace();
0N/A }
0N/A }
0N/A
0N/A private static FileSystemProvider getZipFSProvider() {
0N/A for (FileSystemProvider provider : FileSystemProvider.installedProviders()) {
0N/A if ("jar".equals(provider.getScheme()))
0N/A return provider;
0N/A }
0N/A return null;
0N/A }
0N/A
0N/A @SuppressWarnings("unused")
0N/A /**
0N/A * Not used in demo, but included for demonstrational purposes.
0N/A */
0N/A private static byte[] getBytes(String name) {
0N/A return name.getBytes();
0N/A }
0N/A
0N/A @SuppressWarnings("unused")
0N/A /**
0N/A * Not used in demo, but included for demonstrational purposes.
0N/A */
0N/A private static String getString(byte[] name) {
0N/A return new String(name);
0N/A }
0N/A
0N/A private static void walk(Path path) throws IOException
0N/A {
0N/A Files.walkFileTree(
0N/A path,
0N/A new SimpleFileVisitor<Path>() {
0N/A private int indent = 0;
0N/A private void indent() {
0N/A int n = 0;
0N/A while (n++ < indent)
System.out.printf(" ");
}
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs)
{
indent();
System.out.printf("%s%n", file.getFileName().toString());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs)
{
indent();
System.out.printf("[%s]%n", dir.toString());
indent += 2;
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir,
IOException ioe)
{
indent -= 2;
return FileVisitResult.CONTINUE;
}
});
}
private static void update(FileSystem fs, String path) throws Throwable{
Path src = FileSystems.getDefault().getPath(path);
if (Files.isDirectory(src)) {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(src)) {
for (Path child : ds)
update(fs, child.toString());
}
} else {
Path dst = fs.getPath(path);
Path parent = dst.getParent();
if (parent != null && Files.notExists(parent))
mkdirs(parent);
Files.copy(src, dst, REPLACE_EXISTING);
}
}
private static void extract(FileSystem fs, String path) throws Throwable{
Path src = fs.getPath(path);
if (Files.isDirectory(src)) {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(src)) {
for (Path child : ds)
extract(fs, child.toString());
}
} else {
if (path.startsWith("/"))
path = path.substring(1);
Path dst = FileSystems.getDefault().getPath(path);
Path parent = dst.getParent();
if (Files.notExists(parent))
mkdirs(parent);
Files.copy(src, dst, REPLACE_EXISTING);
}
}
// use DirectoryStream
private static void z2zcopy(FileSystem src, FileSystem dst, String path)
throws IOException
{
Path srcPath = src.getPath(path);
Path dstPath = dst.getPath(path);
if (Files.isDirectory(srcPath)) {
if (!Files.exists(dstPath)) {
try {
mkdirs(dstPath);
} catch (FileAlreadyExistsException x) {}
}
try (DirectoryStream<Path> ds = Files.newDirectoryStream(srcPath)) {
for (Path child : ds) {
z2zcopy(src, dst,
path + (path.endsWith("/")?"":"/") + child.getFileName());
}
}
} else {
//System.out.println("copying..." + path);
Files.copy(srcPath, dstPath);
}
}
// use TreeWalk to move
private static void z2zmove(FileSystem src, FileSystem dst, String path)
throws IOException
{
final Path srcPath = src.getPath(path).toAbsolutePath();
final Path dstPath = dst.getPath(path).toAbsolutePath();
Files.walkFileTree(srcPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs)
{
Path dst = srcPath.relativize(file);
dst = dstPath.resolve(dst);
try {
Path parent = dstPath.getParent();
if (parent != null && Files.notExists(parent))
mkdirs(parent);
Files.move(file, dst);
} catch (IOException x) {
x.printStackTrace();
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs)
{
Path dst = srcPath.relativize(dir);
dst = dstPath.resolve(dst);
try {
if (Files.notExists(dst))
mkdirs(dst);
} catch (IOException x) {
x.printStackTrace();
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir,
IOException ioe)
throws IOException
{
try {
Files.delete(dir);
} catch (IOException x) {
//x.printStackTrace();
}
return FileVisitResult.CONTINUE;
}
});
}
private static void mkdirs(Path path) throws IOException {
path = path.toAbsolutePath();
Path parent = path.getParent();
if (parent != null) {
if (Files.notExists(parent))
mkdirs(parent);
}
Files.createDirectory(path);
}
@SuppressWarnings("unused")
/**
* Not used in demo, but included for demonstrational purposes.
*/
private static void rmdirs(Path path) throws IOException {
while (path != null && path.getNameCount() != 0) {
Files.delete(path);
path = path.getParent();
}
}
private static void list(Path path, boolean verbose ) throws IOException {
if (!"/".equals(path.toString())) {
System.out.printf(" %s%n", path.toString());
if (verbose)
System.out.println(Files.readAttributes(path, BasicFileAttributes.class).toString());
}
if (Files.notExists(path))
return;
if (Files.isDirectory(path)) {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
for (Path child : ds)
list(child, verbose);
}
}
}
@SuppressWarnings("unused")
/**
* Checks that the content of two paths are equal.
* Not used in demo, but included for demonstrational purposes.
*/
private static void checkEqual(Path src, Path dst) throws IOException
{
//System.out.printf("checking <%s> vs <%s>...%n",
// src.toString(), dst.toString());
//streams
byte[] bufSrc = new byte[8192];
byte[] bufDst = new byte[8192];
try (InputStream isSrc = Files.newInputStream(src);
InputStream isDst = Files.newInputStream(dst))
{
int nSrc = 0;
while ((nSrc = isSrc.read(bufSrc)) != -1) {
int nDst = 0;
while (nDst < nSrc) {
int n = isDst.read(bufDst, nDst, nSrc - nDst);
if (n == -1) {
System.out.printf("checking <%s> vs <%s>...%n",
src.toString(), dst.toString());
throw new RuntimeException("CHECK FAILED!");
}
nDst += n;
}
while (--nSrc >= 0) {
if (bufSrc[nSrc] != bufDst[nSrc]) {
System.out.printf("checking <%s> vs <%s>...%n",
src.toString(), dst.toString());
throw new RuntimeException("CHECK FAILED!");
}
nSrc--;
}
}
}
// channels
try (SeekableByteChannel chSrc = Files.newByteChannel(src);
SeekableByteChannel chDst = Files.newByteChannel(dst))
{
if (chSrc.size() != chDst.size()) {
System.out.printf("src[%s].size=%d, dst[%s].size=%d%n",
chSrc.toString(), chSrc.size(),
chDst.toString(), chDst.size());
throw new RuntimeException("CHECK FAILED!");
}
ByteBuffer bbSrc = ByteBuffer.allocate(8192);
ByteBuffer bbDst = ByteBuffer.allocate(8192);
int nSrc = 0;
while ((nSrc = chSrc.read(bbSrc)) != -1) {
int nDst = chDst.read(bbDst);
if (nSrc != nDst) {
System.out.printf("checking <%s> vs <%s>...%n",
src.toString(), dst.toString());
throw new RuntimeException("CHECK FAILED!");
}
while (--nSrc >= 0) {
if (bbSrc.get(nSrc) != bbDst.get(nSrc)) {
System.out.printf("checking <%s> vs <%s>...%n",
src.toString(), dst.toString());
throw new RuntimeException("CHECK FAILED!");
}
nSrc--;
}
bbSrc.flip();
bbDst.flip();
}
} catch (IOException x) {
x.printStackTrace();
}
}
private static void fchCopy(Path src, Path dst) throws IOException
{
Set<OpenOption> read = new HashSet<>();
read.add(READ);
Set<OpenOption> openwrite = new HashSet<>();
openwrite.add(CREATE_NEW);
openwrite.add(WRITE);
try (FileChannel srcFc = src.getFileSystem().provider().newFileChannel(src, read);
FileChannel dstFc = dst.getFileSystem().provider().newFileChannel(dst, openwrite))
{
ByteBuffer bb = ByteBuffer.allocate(8192);
while (srcFc.read(bb) >= 0) {
bb.flip();
dstFc.write(bb);
bb.clear();
}
}
}
private static void chCopy(Path src, Path dst) throws IOException
{
Set<OpenOption> read = new HashSet<>();
read.add(READ);
Set<OpenOption> openwrite = new HashSet<>();
openwrite.add(CREATE_NEW);
openwrite.add(WRITE);
try (SeekableByteChannel srcCh = Files.newByteChannel(src, read);
SeekableByteChannel dstCh = Files.newByteChannel(dst, openwrite))
{
ByteBuffer bb = ByteBuffer.allocate(8192);
while (srcCh.read(bb) >= 0) {
bb.flip();
dstCh.write(bb);
bb.clear();
}
}
}
private static void streamCopy(Path src, Path dst) throws IOException
{
byte[] buf = new byte[8192];
try (InputStream isSrc = Files.newInputStream(src);
OutputStream osDst = Files.newOutputStream(dst))
{
int n = 0;
while ((n = isSrc.read(buf)) != -1) {
osDst.write(buf, 0, n);
}
}
}
}