Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/demo/nio/zipfs/Demo.java
38829 views
/*1* Copyright (c) 2010 Oracle and/or its affiliates. All rights reserved.2*3* Redistribution and use in source and binary forms, with or without4* modification, are permitted provided that the following conditions5* are met:6*7* - Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9*10* - Redistributions in binary form must reproduce the above copyright11* notice, this list of conditions and the following disclaimer in the12* documentation and/or other materials provided with the distribution.13*14* - Neither the name of Oracle nor the names of its15* contributors may be used to endorse or promote products derived16* from this software without specific prior written permission.17*18* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS19* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,20* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR21* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR22* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,23* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,24* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29*/3031/*32* This source code is provided to illustrate the usage of a given feature33* or technique and has been deliberately simplified. Additional steps34* required for a production-quality application, such as security checks,35* input validation and proper error handling, might not be present in36* this sample code.37*/383940import java.io.*;41import java.nio.*;42import java.nio.channels.*;43import java.nio.file.*;44import java.nio.file.spi.*;45import java.nio.file.attribute.*;46import java.net.*;47import java.text.DateFormat;48import java.text.SimpleDateFormat;49import java.util.*;5051import static java.nio.file.StandardOpenOption.*;52import static java.nio.file.StandardCopyOption.*;53/*54* ZipFileSystem usage demo55*56* java Demo action ZipfileName [...]57*58* @author Xueming Shen59*/6061public class Demo {6263static enum Action {64rename, // <java Demo rename zipfile src dst>65// rename entry src to dst inside zipfile6667movein, // <java Demo movein zipfile src dst>68// move an external src file into zipfile69// as entry dst7071moveout, // <java Demo moveout zipfile src dst>72// move a zipfile entry src out to dst7374copy, // <java Demo copy zipfile src dst>75// copy entry src to dst inside zipfile7677copyin, // <java Demo copyin zipfile src dst>78// copy an external src file into zipfile79// as entry dst8081copyin_attrs, // <java Demo copyin_attrs zipfile src dst>82// copy an external src file into zipfile83// as entry dst, with attributes (timestamp)8485copyout, // <java Demo copyout zipfile src dst>86// copy zipfile entry src" out to file dst8788copyout_attrs, // <java Demo copyout_attrs zipfile src dst>8990zzmove, // <java Demo zzmove zfsrc zfdst path>91// move entry path/dir from zfsrc to zfdst9293zzcopy, // <java Demo zzcopy zfsrc zfdst path>94// copy path from zipfile zfsrc to zipfile95// zfdst9697attrs, // <java Demo attrs zipfile path>98// printout the attributes of entry path99100attrsspace, // <java Demo attrsspace zipfile path>101// printout the storespace attrs of entry path102103setmtime, // <java Demo setmtime zipfile "MM/dd/yy-HH:mm:ss" path...>104// set the lastModifiedTime of entry path105106setatime, // <java Demo setatime zipfile "MM/dd/yy-HH:mm:ss" path...>107setctime, // <java Demo setctime zipfile "MM/dd/yy-HH:mm:ss" path...>108109lsdir, // <java Demo lsdir zipfile dir>110// list dir's direct child files/dirs111112mkdir, // <java Demo mkdir zipfile dir>113114mkdirs, // <java Demo mkdirs zipfile dir>115116rmdirs, // <java Demo rmdirs zipfile dir>117118list, // <java Demo list zipfile [dir]>119// recursively list all entries of dir120// via DirectoryStream121122tlist, // <java Demo tlist zipfile [dir]>123// list with buildDirTree=true124125vlist, // <java Demo vlist zipfile [dir]>126// recursively verbose list all entries of127// dir via DirectoryStream128129walk, // <java Demo walk zipfile [dir]>130// recursively walk all entries of dir131// via Files.walkFileTree132133twalk, // <java Demo twalk zipfile [dir]>134// walk with buildDirTree=true135136extract, // <java Demo extract zipfile file [...]>137138update, // <java Demo extract zipfile file [...]>139140delete, // <java Demo delete zipfile file [...]>141142add, // <java Demo add zipfile file [...]>143144create, // <java Demo create zipfile file [...]>145// create a new zipfile if it doesn't exit146// and then add the file(s) into it.147148attrs2, // <java Demo attrs2 zipfile file [...]>149// test different ways to print attrs150151prof,152}153154public static void main(String[] args) throws Throwable {155FileSystemProvider provider = getZipFSProvider();156if (provider == null) {157System.err.println("ZIP filesystem provider is not installed");158System.exit(1);159}160161Action action = Action.valueOf(args[0]);162Map<String, Object> env = env = new HashMap<>();163if (action == Action.create)164env.put("create", "true");165try (FileSystem fs = provider.newFileSystem(Paths.get(args[1]), env)) {166Path path, src, dst;167switch (action) {168case rename:169src = fs.getPath(args[2]);170dst = fs.getPath(args[3]);171Files.move(src, dst);172break;173case moveout:174src = fs.getPath(args[2]);175dst = Paths.get(args[3]);176Files.move(src, dst);177break;178case movein:179src = Paths.get(args[2]);180dst = fs.getPath(args[3]);181Files.move(src, dst);182break;183case copy:184src = fs.getPath(args[2]);185dst = fs.getPath(args[3]);186Files.copy(src, dst);187break;188case copyout:189src = fs.getPath(args[2]);190dst = Paths.get(args[3]);191Files.copy(src, dst);192break;193case copyin:194src = Paths.get(args[2]);195dst = fs.getPath(args[3]);196Files.copy(src, dst);197break;198case copyin_attrs:199src = Paths.get(args[2]);200dst = fs.getPath(args[3]);201Files.copy(src, dst, COPY_ATTRIBUTES);202break;203case copyout_attrs:204src = fs.getPath(args[2]);205dst = Paths.get(args[3]);206Files.copy(src, dst, COPY_ATTRIBUTES);207break;208case zzmove:209try (FileSystem fs2 = provider.newFileSystem(Paths.get(args[2]), env)) {210z2zmove(fs, fs2, args[3]);211}212break;213case zzcopy:214try (FileSystem fs2 = provider.newFileSystem(Paths.get(args[2]), env)) {215z2zcopy(fs, fs2, args[3]);216}217break;218case attrs:219for (int i = 2; i < args.length; i++) {220path = fs.getPath(args[i]);221System.out.println(path);222System.out.println(223Files.readAttributes(path, BasicFileAttributes.class).toString());224}225break;226case setmtime:227DateFormat df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");228Date newDatetime = df.parse(args[2]);229for (int i = 3; i < args.length; i++) {230path = fs.getPath(args[i]);231Files.setAttribute(path, "lastModifiedTime",232FileTime.fromMillis(newDatetime.getTime()));233System.out.println(234Files.readAttributes(path, BasicFileAttributes.class).toString());235}236break;237case setctime:238df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");239newDatetime = df.parse(args[2]);240for (int i = 3; i < args.length; i++) {241path = fs.getPath(args[i]);242Files.setAttribute(path, "creationTime",243FileTime.fromMillis(newDatetime.getTime()));244System.out.println(245Files.readAttributes(path, BasicFileAttributes.class).toString());246}247break;248case setatime:249df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");250newDatetime = df.parse(args[2]);251for (int i = 3; i < args.length; i++) {252path = fs.getPath(args[i]);253Files.setAttribute(path, "lastAccessTime",254FileTime.fromMillis(newDatetime.getTime()));255System.out.println(256Files.readAttributes(path, BasicFileAttributes.class).toString());257}258break;259case attrsspace:260path = fs.getPath("/");261FileStore fstore = Files.getFileStore(path);262System.out.printf("filestore[%s]%n", fstore.name());263System.out.printf(" totalSpace: %d%n",264(Long)fstore.getAttribute("totalSpace"));265System.out.printf(" usableSpace: %d%n",266(Long)fstore.getAttribute("usableSpace"));267System.out.printf(" unallocSpace: %d%n",268(Long)fstore.getAttribute("unallocatedSpace"));269break;270case list:271case tlist:272if (args.length < 3)273list(fs.getPath("/"), false);274else275list(fs.getPath(args[2]), false);276break;277case vlist:278if (args.length < 3)279list(fs.getPath("/"), true);280else281list(fs.getPath(args[2]), true);282break;283case twalk:284case walk:285walk(fs.getPath((args.length > 2)? args[2] : "/"));286break;287case extract:288if (args.length == 2) {289extract(fs, "/");290} else {291for (int i = 2; i < args.length; i++) {292extract(fs, args[i]);293}294}295break;296case delete:297for (int i = 2; i < args.length; i++)298Files.delete(fs.getPath(args[i]));299break;300case create:301case add:302case update:303for (int i = 2; i < args.length; i++) {304update(fs, args[i]);305}306break;307case lsdir:308path = fs.getPath(args[2]);309final String fStr = (args.length > 3)?args[3]:"";310try (DirectoryStream<Path> ds = Files.newDirectoryStream(path,311new DirectoryStream.Filter<Path>() {312@Override313public boolean accept(Path path) {314return path.toString().contains(fStr);315}316}))317{318for (Path p : ds)319System.out.println(p);320}321break;322case mkdir:323Files.createDirectory(fs.getPath(args[2]));324break;325case mkdirs:326mkdirs(fs.getPath(args[2]));327break;328case attrs2:329for (int i = 2; i < args.length; i++) {330path = fs.getPath(args[i]);331System.out.printf("%n%s%n", path);332System.out.println("-------(1)---------");333System.out.println(334Files.readAttributes(path, BasicFileAttributes.class).toString());335System.out.println("-------(2)---------");336Map<String, Object> map = Files.readAttributes(path, "zip:*");337for (Map.Entry<String, Object> e : map.entrySet()) {338System.out.printf(" %s : %s%n", e.getKey(), e.getValue());339}340System.out.println("-------(3)---------");341map = Files.readAttributes(path, "size,lastModifiedTime,isDirectory");342for (Map.Entry<String, ?> e : map.entrySet()) {343System.out.printf(" %s : %s%n", e.getKey(), e.getValue());344}345}346break;347case prof:348list(fs.getPath("/"), false);349while (true) {350Thread.sleep(10000);351//list(fs.getPath("/"), true);352System.out.println("sleeping...");353}354}355} catch (Exception x) {356x.printStackTrace();357}358}359360private static FileSystemProvider getZipFSProvider() {361for (FileSystemProvider provider : FileSystemProvider.installedProviders()) {362if ("jar".equals(provider.getScheme()))363return provider;364}365return null;366}367368@SuppressWarnings("unused")369/**370* Not used in demo, but included for demonstrational purposes.371*/372private static byte[] getBytes(String name) {373return name.getBytes();374}375376@SuppressWarnings("unused")377/**378* Not used in demo, but included for demonstrational purposes.379*/380private static String getString(byte[] name) {381return new String(name);382}383384private static void walk(Path path) throws IOException385{386Files.walkFileTree(387path,388new SimpleFileVisitor<Path>() {389private int indent = 0;390private void indent() {391int n = 0;392while (n++ < indent)393System.out.printf(" ");394}395396@Override397public FileVisitResult visitFile(Path file,398BasicFileAttributes attrs)399{400indent();401System.out.printf("%s%n", file.getFileName().toString());402return FileVisitResult.CONTINUE;403}404405@Override406public FileVisitResult preVisitDirectory(Path dir,407BasicFileAttributes attrs)408{409indent();410System.out.printf("[%s]%n", dir.toString());411indent += 2;412return FileVisitResult.CONTINUE;413}414415@Override416public FileVisitResult postVisitDirectory(Path dir,417IOException ioe)418{419indent -= 2;420return FileVisitResult.CONTINUE;421}422});423}424425private static void update(FileSystem fs, String path) throws Throwable{426Path src = FileSystems.getDefault().getPath(path);427if (Files.isDirectory(src)) {428try (DirectoryStream<Path> ds = Files.newDirectoryStream(src)) {429for (Path child : ds)430update(fs, child.toString());431}432} else {433Path dst = fs.getPath(path);434Path parent = dst.getParent();435if (parent != null && Files.notExists(parent))436mkdirs(parent);437Files.copy(src, dst, REPLACE_EXISTING);438}439}440441private static void extract(FileSystem fs, String path) throws Throwable{442Path src = fs.getPath(path);443if (Files.isDirectory(src)) {444try (DirectoryStream<Path> ds = Files.newDirectoryStream(src)) {445for (Path child : ds)446extract(fs, child.toString());447}448} else {449if (path.startsWith("/"))450path = path.substring(1);451Path dst = FileSystems.getDefault().getPath(path);452Path parent = dst.getParent();453if (Files.notExists(parent))454mkdirs(parent);455Files.copy(src, dst, REPLACE_EXISTING);456}457}458459// use DirectoryStream460private static void z2zcopy(FileSystem src, FileSystem dst, String path)461throws IOException462{463Path srcPath = src.getPath(path);464Path dstPath = dst.getPath(path);465466if (Files.isDirectory(srcPath)) {467if (!Files.exists(dstPath)) {468try {469mkdirs(dstPath);470} catch (FileAlreadyExistsException x) {}471}472try (DirectoryStream<Path> ds = Files.newDirectoryStream(srcPath)) {473for (Path child : ds) {474z2zcopy(src, dst,475path + (path.endsWith("/")?"":"/") + child.getFileName());476}477}478} else {479//System.out.println("copying..." + path);480Files.copy(srcPath, dstPath);481}482}483484// use TreeWalk to move485private static void z2zmove(FileSystem src, FileSystem dst, String path)486throws IOException487{488final Path srcPath = src.getPath(path).toAbsolutePath();489final Path dstPath = dst.getPath(path).toAbsolutePath();490491Files.walkFileTree(srcPath, new SimpleFileVisitor<Path>() {492493@Override494public FileVisitResult visitFile(Path file,495BasicFileAttributes attrs)496{497Path dst = srcPath.relativize(file);498dst = dstPath.resolve(dst);499try {500Path parent = dstPath.getParent();501if (parent != null && Files.notExists(parent))502mkdirs(parent);503Files.move(file, dst);504} catch (IOException x) {505x.printStackTrace();506}507return FileVisitResult.CONTINUE;508}509510@Override511public FileVisitResult preVisitDirectory(Path dir,512BasicFileAttributes attrs)513{514Path dst = srcPath.relativize(dir);515dst = dstPath.resolve(dst);516try {517518if (Files.notExists(dst))519mkdirs(dst);520} catch (IOException x) {521x.printStackTrace();522}523return FileVisitResult.CONTINUE;524}525526@Override527public FileVisitResult postVisitDirectory(Path dir,528IOException ioe)529throws IOException530{531try {532Files.delete(dir);533} catch (IOException x) {534//x.printStackTrace();535}536return FileVisitResult.CONTINUE;537}538});539540}541542private static void mkdirs(Path path) throws IOException {543path = path.toAbsolutePath();544Path parent = path.getParent();545if (parent != null) {546if (Files.notExists(parent))547mkdirs(parent);548}549Files.createDirectory(path);550}551552@SuppressWarnings("unused")553/**554* Not used in demo, but included for demonstrational purposes.555*/556private static void rmdirs(Path path) throws IOException {557while (path != null && path.getNameCount() != 0) {558Files.delete(path);559path = path.getParent();560}561}562563private static void list(Path path, boolean verbose ) throws IOException {564if (!"/".equals(path.toString())) {565System.out.printf(" %s%n", path.toString());566if (verbose)567System.out.println(Files.readAttributes(path, BasicFileAttributes.class).toString());568}569if (Files.notExists(path))570return;571if (Files.isDirectory(path)) {572try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {573for (Path child : ds)574list(child, verbose);575}576}577}578579@SuppressWarnings("unused")580/**581* Checks that the content of two paths are equal.582* Not used in demo, but included for demonstrational purposes.583*/584private static void checkEqual(Path src, Path dst) throws IOException585{586//System.out.printf("checking <%s> vs <%s>...%n",587// src.toString(), dst.toString());588589//streams590byte[] bufSrc = new byte[8192];591byte[] bufDst = new byte[8192];592try (InputStream isSrc = Files.newInputStream(src);593InputStream isDst = Files.newInputStream(dst))594{595int nSrc = 0;596while ((nSrc = isSrc.read(bufSrc)) != -1) {597int nDst = 0;598while (nDst < nSrc) {599int n = isDst.read(bufDst, nDst, nSrc - nDst);600if (n == -1) {601System.out.printf("checking <%s> vs <%s>...%n",602src.toString(), dst.toString());603throw new RuntimeException("CHECK FAILED!");604}605nDst += n;606}607while (--nSrc >= 0) {608if (bufSrc[nSrc] != bufDst[nSrc]) {609System.out.printf("checking <%s> vs <%s>...%n",610src.toString(), dst.toString());611throw new RuntimeException("CHECK FAILED!");612}613nSrc--;614}615}616}617618// channels619620try (SeekableByteChannel chSrc = Files.newByteChannel(src);621SeekableByteChannel chDst = Files.newByteChannel(dst))622{623if (chSrc.size() != chDst.size()) {624System.out.printf("src[%s].size=%d, dst[%s].size=%d%n",625chSrc.toString(), chSrc.size(),626chDst.toString(), chDst.size());627throw new RuntimeException("CHECK FAILED!");628}629ByteBuffer bbSrc = ByteBuffer.allocate(8192);630ByteBuffer bbDst = ByteBuffer.allocate(8192);631632int nSrc = 0;633while ((nSrc = chSrc.read(bbSrc)) != -1) {634int nDst = chDst.read(bbDst);635if (nSrc != nDst) {636System.out.printf("checking <%s> vs <%s>...%n",637src.toString(), dst.toString());638throw new RuntimeException("CHECK FAILED!");639}640while (--nSrc >= 0) {641if (bbSrc.get(nSrc) != bbDst.get(nSrc)) {642System.out.printf("checking <%s> vs <%s>...%n",643src.toString(), dst.toString());644throw new RuntimeException("CHECK FAILED!");645}646nSrc--;647}648bbSrc.flip();649bbDst.flip();650}651} catch (IOException x) {652x.printStackTrace();653}654}655656private static void fchCopy(Path src, Path dst) throws IOException657{658Set<OpenOption> read = new HashSet<>();659read.add(READ);660Set<OpenOption> openwrite = new HashSet<>();661openwrite.add(CREATE_NEW);662openwrite.add(WRITE);663664try (FileChannel srcFc = src.getFileSystem().provider().newFileChannel(src, read);665FileChannel dstFc = dst.getFileSystem().provider().newFileChannel(dst, openwrite))666{667ByteBuffer bb = ByteBuffer.allocate(8192);668while (srcFc.read(bb) >= 0) {669bb.flip();670dstFc.write(bb);671bb.clear();672}673}674}675676private static void chCopy(Path src, Path dst) throws IOException677{678Set<OpenOption> read = new HashSet<>();679read.add(READ);680Set<OpenOption> openwrite = new HashSet<>();681openwrite.add(CREATE_NEW);682openwrite.add(WRITE);683684try (SeekableByteChannel srcCh = Files.newByteChannel(src, read);685SeekableByteChannel dstCh = Files.newByteChannel(dst, openwrite))686{687ByteBuffer bb = ByteBuffer.allocate(8192);688while (srcCh.read(bb) >= 0) {689bb.flip();690dstCh.write(bb);691bb.clear();692}693}694}695696private static void streamCopy(Path src, Path dst) throws IOException697{698byte[] buf = new byte[8192];699try (InputStream isSrc = Files.newInputStream(src);700OutputStream osDst = Files.newOutputStream(dst))701{702int n = 0;703while ((n = isSrc.read(buf)) != -1) {704osDst.write(buf, 0, n);705}706}707}708}709710711