提交 e3b58020 编写于 作者: S sherman

7015391: (zipfs) Update zip provider for 1/2011 changes

7014948: (zipfs) ZipFileSystem.newFileSystem(Path...) should not throw FileSystemAlreadyExistsException
7015139: (zipfs) ZipPath.delete() should throw DirectoryNotEmptyException when handling "real, non-empty" dir
Summary: zip filesystem provider update
Reviewed-by: alanb
上级 7e99b424
......@@ -31,7 +31,7 @@ BUILDDIR = ..
PRODUCT = demos
include $(BUILDDIR)/common/Defs.gmk
SUBDIRS = jni
SUBDIRS = jni nio
SUBDIRS_desktop = applets jfc
SUBDIRS_management = management
SUBDIRS_misc = scripting
......
此差异已折叠。
......@@ -5,9 +5,8 @@ The factory methods defined by the java.nio.file.FileSystems class can be
used to create a FileSystem, eg:
// use file type detection
Map<String,?> env = Collections.emptyMap();
Path jarfile = Paths.get("foo.jar");
FileSystem fs = FileSystems.newFileSystem(jarfile, env, null);
FileSystem fs = FileSystems.newFileSystem(jarfile, null);
-or
......
......@@ -32,11 +32,10 @@
package com.sun.nio.zipfs;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.FileAttributeView;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.*;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
/*
* @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal
......@@ -122,25 +121,19 @@ public class ZipFileAttributeView implements BasicFileAttributeView
"' is unknown or read-only attribute");
}
public Object getAttribute(String attribute, boolean domap)
Map<String, Object> readAttributes(String attributes)
throws IOException
{
ZipFileAttributes zfas = readAttributes();
if (!domap) {
try {
return attribute(AttrID.valueOf(attribute), zfas);
} catch (IllegalArgumentException x) {}
return null;
}
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
if ("*".equals(attribute)) {
if ("*".equals(attributes)) {
for (AttrID id : AttrID.values()) {
try {
map.put(id.name(), attribute(id, zfas));
} catch (IllegalArgumentException x) {}
}
} else {
String[] as = attribute.split(",");
String[] as = attributes.split(",");
for (String a : as) {
try {
map.put(a, attribute(AttrID.valueOf(a), zfas));
......
......@@ -32,14 +32,13 @@
package com.sun.nio.zipfs;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.FileStore;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileAttributeView;
import java.nio.file.attribute.FileStoreAttributeView;
import java.nio.file.attribute.FileStoreSpaceAttributeView;
import java.nio.file.attribute.FileStoreSpaceAttributes;
import java.nio.file.attribute.Attributes;
import java.nio.file.attribute.BasicFileAttributeView;
import java.util.Formatter;
......@@ -87,71 +86,61 @@ public class ZipFileStore extends FileStore {
public <V extends FileStoreAttributeView> V getFileStoreAttributeView(Class<V> type) {
if (type == null)
throw new NullPointerException();
if (type == FileStoreSpaceAttributeView.class)
return (V) new ZipFileStoreAttributeView(this);
return null;
return (V)null;
}
@Override
public long getTotalSpace() throws IOException {
return new ZipFileStoreAttributes(this).totalSpace();
}
@Override
public long getUsableSpace() throws IOException {
return new ZipFileStoreAttributes(this).usableSpace();
}
@Override
public long getUnallocatedSpace() throws IOException {
return new ZipFileStoreAttributes(this).unallocatedSpace();
}
@Override
public Object getAttribute(String attribute) throws IOException {
if (attribute.equals("space:totalSpace"))
return new ZipFileStoreAttributeView(this).readAttributes().totalSpace();
if (attribute.equals("space:usableSpace"))
return new ZipFileStoreAttributeView(this).readAttributes().usableSpace();
if (attribute.equals("space:unallocatedSpace"))
return new ZipFileStoreAttributeView(this).readAttributes().unallocatedSpace();
if (attribute.equals("totalSpace"))
return getTotalSpace();
if (attribute.equals("usableSpace"))
return getUsableSpace();
if (attribute.equals("unallocatedSpace"))
return getUnallocatedSpace();
throw new UnsupportedOperationException("does not support the given attribute");
}
private static class ZipFileStoreAttributeView implements FileStoreSpaceAttributeView {
private static class ZipFileStoreAttributes {
final FileStore fstore;
final long size;
private final ZipFileStore fileStore;
public ZipFileStoreAttributes(ZipFileStore fileStore)
throws IOException
{
Path path = FileSystems.getDefault().getPath(fileStore.name());
this.size = Files.size(path);
this.fstore = Files.getFileStore(path);
}
public ZipFileStoreAttributeView(ZipFileStore fileStore) {
this.fileStore = fileStore;
public long totalSpace() {
return size;
}
@Override
public String name() {
return "space";
public long usableSpace() throws IOException {
if (!fstore.isReadOnly())
return fstore.getUsableSpace();
return 0;
}
@Override
public FileStoreSpaceAttributes readAttributes() throws IOException {
final String file = fileStore.name();
Path path = FileSystems.getDefault().getPath(file);
final long size = Attributes.readBasicFileAttributes(path).size();
final FileStore fstore = path.getFileStore();
final FileStoreSpaceAttributes fstoreAttrs =
Attributes.readFileStoreSpaceAttributes(fstore);
return new FileStoreSpaceAttributes() {
public long totalSpace() {
return size;
}
public long usableSpace() {
if (!fstore.isReadOnly())
return fstoreAttrs.usableSpace();
return 0;
}
public long unallocatedSpace() {
if (!fstore.isReadOnly())
return fstoreAttrs.unallocatedSpace();
return 0;
}
public String toString() {
StringBuilder sb = new StringBuilder();
Formatter fm = new Formatter(sb);
fm.format("FileStoreSpaceAttributes[%s]%n", file);
fm.format(" totalSpace: %d%n", totalSpace());
fm.format(" usableSpace: %d%n", usableSpace());
fm.format(" unallocSpace: %d%n", unallocatedSpace());
fm.close();
return sb.toString();
}
};
public long unallocatedSpace() throws IOException {
if (!fstore.isReadOnly())
return fstore.getUnallocatedSpace();
return 0;
}
}
}
......@@ -101,24 +101,25 @@ public class ZipFileSystem extends FileSystem {
this.provider = provider;
this.zfpath = zfpath;
if (zfpath.notExists()) {
if (Files.notExists(zfpath)) {
if (createNew) {
OutputStream os = zfpath.newOutputStream(CREATE_NEW, WRITE);
new END().write(os, 0);
os.close();
try (OutputStream os = Files.newOutputStream(zfpath, CREATE_NEW, WRITE)) {
new END().write(os, 0);
}
} else {
throw new FileSystemNotFoundException(zfpath.toString());
}
}
zfpath.checkAccess(AccessMode.READ); // sm and existence check
// sm and existence check
zfpath.getFileSystem().provider().checkAccess(zfpath, AccessMode.READ);
try {
zfpath.checkAccess(AccessMode.WRITE);
zfpath.getFileSystem().provider().checkAccess(zfpath, AccessMode.WRITE);
} catch (AccessDeniedException x) {
this.readOnly = true;
}
this.zc = ZipCoder.get(nameEncoding);
this.defaultdir = new ZipPath(this, getBytes(defaultDir));
this.ch = zfpath.newByteChannel(READ);
this.ch = Files.newByteChannel(zfpath, READ);
this.cen = initCEN();
}
......@@ -159,9 +160,22 @@ public class ZipFileSystem extends FileSystem {
}
@Override
public ZipPath getPath(String path) {
if (path.length() == 0)
throw new InvalidPathException(path, "path should not be empty");
public ZipPath getPath(String first, String... more) {
String path;
if (more.length == 0) {
path = first;
} else {
StringBuilder sb = new StringBuilder();
sb.append(first);
for (String segment: more) {
if (segment.length() > 0) {
if (sb.length() > 0)
sb.append('/');
sb.append(segment);
}
}
path = sb.toString();
}
return new ZipPath(this, getBytes(path));
}
......@@ -268,16 +282,22 @@ public class ZipFileSystem extends FileSystem {
def.end();
}
IOException ioe = null;
synchronized (tmppaths) {
for (Path p: tmppaths) {
try {
p.deleteIfExists();
Files.deleteIfExists(p);
} catch (IOException x) {
x.printStackTrace();
if (ioe == null)
ioe = x;
else
ioe.addSuppressed(x);
}
}
}
provider.removeFileSystem(zfpath);
provider.removeFileSystem(zfpath, this);
if (ioe != null)
throw ioe;
}
ZipFileAttributes getFileAttributes(byte[] path)
......@@ -444,7 +464,7 @@ public class ZipFileSystem extends FileSystem {
u.bytes = Arrays.copyOf(eSrc.bytes, eSrc.bytes.length);
else if (eSrc.file != null) {
u.file = getTempPathForEntry(null);
eSrc.file.copyTo(u.file, REPLACE_EXISTING);
Files.copy(eSrc.file, u.file, REPLACE_EXISTING);
}
}
}
......@@ -778,7 +798,8 @@ public class ZipFileSystem extends FileSystem {
fch.close();
if (forWrite) {
u.mtime = System.currentTimeMillis();
u.size = Attributes.readBasicFileAttributes(u.file).size();
u.size = Files.size(u.file);
update(u);
} else {
if (!isFCH) // if this is a new fch for reading
......@@ -805,13 +826,8 @@ public class ZipFileSystem extends FileSystem {
if (path != null) {
Entry e = getEntry0(path);
if (e != null) {
InputStream is = newInputStream(path);
OutputStream os = tmpPath.newOutputStream(WRITE);
try {
copyStream(is, os);
} finally {
is.close();
os.close();
try (InputStream is = newInputStream(path)) {
Files.copy(is, tmpPath, REPLACE_EXISTING);
}
}
}
......@@ -819,7 +835,7 @@ public class ZipFileSystem extends FileSystem {
}
private void removeTempPathForEntry(Path path) throws IOException {
path.delete();
Files.delete(path);
tmppaths.remove(path);
}
......@@ -1073,11 +1089,11 @@ public class ZipFileSystem extends FileSystem {
// shared key. consumer guarantees the "writeLock" before use it.
private final IndexNode LOOKUPKEY = IndexNode.keyOf(null);
private void updateDelete(Entry e) {
private void updateDelete(IndexNode inode) {
beginWrite();
try {
removeFromTree(e);
inodes.remove(e);
removeFromTree(inode);
inodes.remove(inode);
hasUpdate = true;
} finally {
endWrite();
......@@ -1158,7 +1174,7 @@ public class ZipFileSystem extends FileSystem {
for (ExChannelCloser ecc : exChClosers) {
if (ecc.streams.isEmpty()) {
ecc.ch.close();
ecc.path.delete();
Files.delete(ecc.path);
exChClosers.remove(ecc);
}
}
......@@ -1166,7 +1182,7 @@ public class ZipFileSystem extends FileSystem {
if (!hasUpdate)
return;
Path tmpFile = createTempFileInSameDirectoryAs(zfpath);
OutputStream os = tmpFile.newOutputStream(WRITE);
OutputStream os = Files.newOutputStream(tmpFile, WRITE);
ArrayList<Entry> elist = new ArrayList<>(inodes.size());
long written = 0;
byte[] buf = new byte[8192];
......@@ -1191,26 +1207,26 @@ public class ZipFileSystem extends FileSystem {
os.write(e.bytes); // already
written += e.bytes.length;
} else if (e.file != null) { // tmp file
InputStream is = e.file.newInputStream();
int n;
if (e.type == Entry.NEW) { // deflated already
while ((n = is.read(buf)) != -1) {
os.write(buf, 0, n);
written += n;
try (InputStream is = Files.newInputStream(e.file)) {
int n;
if (e.type == Entry.NEW) { // deflated already
while ((n = is.read(buf)) != -1) {
os.write(buf, 0, n);
written += n;
}
} else if (e.type == Entry.FILECH) {
// the data are not deflated, use ZEOS
try (OutputStream os2 = new EntryOutputStream(e, os)) {
while ((n = is.read(buf)) != -1) {
os2.write(buf, 0, n);
}
}
written += e.csize;
if ((e.flag & FLAG_DATADESCR) != 0)
written += e.writeEXT(os);
}
} else if (e.type == Entry.FILECH) {
// the data are not deflated, use ZEOS
OutputStream os2 = new EntryOutputStream(e, os);
while ((n = is.read(buf)) != -1) {
os2.write(buf, 0, n);
}
os2.close();
written += e.csize;
if ((e.flag & FLAG_DATADESCR) != 0)
written += e.writeEXT(os);
}
is.close();
e.file.delete();
Files.delete(e.file);
tmppaths.remove(e.file);
} else {
// dir, 0-length data
......@@ -1257,15 +1273,15 @@ public class ZipFileSystem extends FileSystem {
createTempFileInSameDirectoryAs(zfpath),
ch,
streams);
zfpath.moveTo(ecc.path, REPLACE_EXISTING);
Files.move(zfpath, ecc.path, REPLACE_EXISTING);
exChClosers.add(ecc);
streams = Collections.synchronizedSet(new HashSet<InputStream>());
} else {
ch.close();
zfpath.delete();
Files.delete(zfpath);
}
tmpFile.moveTo(zfpath, REPLACE_EXISTING);
Files.move(tmpFile, zfpath, REPLACE_EXISTING);
hasUpdate = false; // clear
/*
if (isOpen) {
......@@ -1304,16 +1320,17 @@ public class ZipFileSystem extends FileSystem {
throws IOException
{
checkWritable();
Entry e = getEntry0(path);
if (e == null) {
IndexNode inode = getInode(path);
if (inode == null) {
if (path != null && path.length == 0)
throw new ZipException("root directory </> can't not be delete");
if (failIfNotExists)
throw new NoSuchFileException(getString(path));
} else {
if (e.isDir() && e.child != null)
if (inode.isDir() && inode.child != null)
throw new DirectoryNotEmptyException(getString(path));
updateDelete(e);
updateDelete(inode);
}
}
......@@ -1343,7 +1360,7 @@ public class ZipFileSystem extends FileSystem {
OutputStream os;
if (useTempFile) {
e.file = getTempPathForEntry(null);
os = e.file.newOutputStream(WRITE);
os = Files.newOutputStream(e.file, WRITE);
} else {
os = new ByteArrayOutputStream((e.size > 0)? (int)e.size : 8192);
}
......@@ -1359,12 +1376,12 @@ public class ZipFileSystem extends FileSystem {
if (e.bytes != null)
eis = new ByteArrayInputStream(e.bytes);
else if (e.file != null)
eis = e.file.newInputStream();
eis = Files.newInputStream(e.file);
else
throw new ZipException("update entry data is missing");
} else if (e.type == Entry.FILECH) {
// FILECH result is un-compressed.
eis = e.file.newInputStream();
eis = Files.newInputStream(e.file);
// TBD: wrap to hook close()
// streams.add(eis);
return eis;
......
......@@ -31,23 +31,18 @@
package com.sun.nio.zipfs;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.FileRef;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystemAlreadyExistsException;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.ProviderMismatchException;
import java.nio.file.attribute.FileAttribute;
import java.io.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.nio.file.DirectoryStream.Filter;
import java.nio.file.attribute.*;
import java.nio.file.spi.FileSystemProvider;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
/*
*
......@@ -87,28 +82,25 @@ public class ZipFileSystemProvider extends FileSystemProvider {
public FileSystem newFileSystem(URI uri, Map<String, ?> env)
throws IOException
{
return newFileSystem(uriToPath(uri), env);
return newFileSystem(uriToPath(uri), env, true);
}
@Override
public FileSystem newFileSystem(FileRef file, Map<String, ?> env)
public FileSystem newFileSystem(Path path, Map<String, ?> env)
throws IOException
{
if (!(file instanceof Path))
throw new UnsupportedOperationException();
Path path = (Path)file;
if (!path.toUri().getScheme().equalsIgnoreCase("file")) {
throw new UnsupportedOperationException();
}
return newFileSystem(path, env);
return newFileSystem(path, env, false);
}
private FileSystem newFileSystem(Path path, Map<String, ?> env)
private FileSystem newFileSystem(Path path, Map<String, ?> env, boolean checkIfFSExists)
throws IOException
{
synchronized(filesystems) {
Path realPath = null;
if (path.exists()) {
if (checkIfFSExists && Files.exists(path)) {
realPath = path.toRealPath(true);
if (filesystems.containsKey(realPath))
throw new FileSystemAlreadyExistsException();
......@@ -116,7 +108,8 @@ public class ZipFileSystemProvider extends FileSystemProvider {
ZipFileSystem zipfs = new ZipFileSystem(this, path, env);
if (realPath == null)
realPath = path.toRealPath(true);
filesystems.put(realPath, zipfs);
if (!filesystems.containsKey(realPath))
filesystems.put(realPath, zipfs);
return zipfs;
}
}
......@@ -133,18 +126,6 @@ public class ZipFileSystemProvider extends FileSystemProvider {
return getFileSystem(uri).getPath(spec.substring(sep + 1));
}
@Override
public FileChannel newFileChannel(Path path,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
throws IOException
{
if (path == null)
throw new NullPointerException("path is null");
if (path instanceof ZipPath)
return ((ZipPath)path).newFileChannel(options, attrs);
throw new ProviderMismatchException();
}
@Override
public FileSystem getFileSystem(URI uri) {
......@@ -161,9 +142,155 @@ public class ZipFileSystemProvider extends FileSystemProvider {
}
}
void removeFileSystem(Path zfpath) throws IOException {
// Checks that the given file is a UnixPath
static final ZipPath toZipPath(Path path) {
if (path == null)
throw new NullPointerException();
if (!(path instanceof ZipPath))
throw new ProviderMismatchException();
return (ZipPath)path;
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException {
toZipPath(path).checkAccess(modes);
}
@Override
public void copy(Path src, Path target, CopyOption... options)
throws IOException
{
toZipPath(src).copy(toZipPath(target), options);
}
@Override
public void createDirectory(Path path, FileAttribute<?>... attrs)
throws IOException
{
toZipPath(path).createDirectory(attrs);
}
@Override
public final void delete(Path path) throws IOException {
toZipPath(path).delete();
}
@Override
@SuppressWarnings("unchecked")
public <V extends FileAttributeView> V
getFileAttributeView(Path path, Class<V> type, LinkOption... options)
{
return (V)ZipFileAttributeView.get(toZipPath(path), type);
}
@Override
public FileStore getFileStore(Path path) throws IOException {
return toZipPath(path).getFileStore();
}
@Override
public boolean isHidden(Path path) {
return toZipPath(path).isHidden();
}
@Override
public boolean isSameFile(Path path, Path other) throws IOException {
return toZipPath(path).isSameFile(other);
}
@Override
public void move(Path src, Path target, CopyOption... options)
throws IOException
{
toZipPath(src).move(toZipPath(target), options);
}
@Override
public AsynchronousFileChannel newAsynchronousFileChannel(Path path,
Set<? extends OpenOption> options,
ExecutorService exec,
FileAttribute<?>... attrs)
throws IOException
{
throw new UnsupportedOperationException();
}
@Override
public SeekableByteChannel newByteChannel(Path path,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
throws IOException
{
return toZipPath(path).newByteChannel(options, attrs);
}
@Override
public DirectoryStream<Path> newDirectoryStream(
Path path, Filter<? super Path> filter) throws IOException
{
return toZipPath(path).newDirectoryStream(filter);
}
@Override
public FileChannel newFileChannel(Path path,
Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
throws IOException
{
return toZipPath(path).newFileChannel(options, attrs);
}
@Override
public InputStream newInputStream(Path path, OpenOption... options)
throws IOException
{
return toZipPath(path).newInputStream(options);
}
@Override
public OutputStream newOutputStream(Path path, OpenOption... options)
throws IOException
{
return toZipPath(path).newOutputStream(options);
}
@Override
public <A extends BasicFileAttributes> A
readAttributes(Path path, Class<A> type, LinkOption... options)
throws IOException
{
if (type == BasicFileAttributes.class || type == ZipFileAttributes.class)
return (A)toZipPath(path).getAttributes();
return null;
}
@Override
public Map<String, Object>
readAttributes(Path path, String attribute, LinkOption... options)
throws IOException
{
return toZipPath(path).readAttributes(attribute, options);
}
@Override
public Path readSymbolicLink(Path link) throws IOException {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public void setAttribute(Path path, String attribute,
Object value, LinkOption... options)
throws IOException
{
toZipPath(path).setAttribute(attribute, value, options);
}
//////////////////////////////////////////////////////////////
void removeFileSystem(Path zfpath, ZipFileSystem zfs) throws IOException {
synchronized (filesystems) {
filesystems.remove(zfpath.toRealPath(true));
zfpath = zfpath.toRealPath(true);
if (filesystems.get(zfpath) == zfs)
filesystems.remove(zfpath);
}
}
}
......@@ -31,29 +31,23 @@
package com.sun.nio.zipfs;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.*;
import java.net.URI;
import java.nio.channels.FileChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.channels.*;
import java.nio.file.*;
import java.nio.file.DirectoryStream.Filter;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.FileAttributeView;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.*;
import java.util.*;
import static java.nio.file.StandardOpenOption.*;
import static java.nio.file.StandardCopyOption.*;
/**
*
* @author Xueming Shen, Rajendra Gutupalli,Jaya Hangal
*/
public class ZipPath extends Path {
public class ZipPath implements Path {
private final ZipFileSystem zfs;
private final byte[] path;
......@@ -82,7 +76,7 @@ public class ZipPath extends Path {
}
@Override
public Path getName() {
public Path getFileName() {
initOffsets();
int count = offsets.length;
if (count == 0)
......@@ -162,8 +156,7 @@ public class ZipPath extends Path {
return realPath;
}
@Override
public boolean isHidden() {
boolean isHidden() {
return false;
}
......@@ -230,7 +223,7 @@ public class ZipPath extends Path {
public Path relativize(Path other) {
final ZipPath o = checkPath(other);
if (o.equals(this))
return null;
return new ZipPath(getFileSystem(), new byte[0], true);
if (/* this.getFileSystem() != o.getFileSystem() || */
this.isAbsolute() != o.isAbsolute()) {
throw new IllegalArgumentException();
......@@ -277,8 +270,6 @@ public class ZipPath extends Path {
@Override
public ZipPath resolve(Path other) {
if (other == null)
return this;
final ZipPath o = checkPath(other);
if (o.isAbsolute())
return o;
......@@ -297,8 +288,11 @@ public class ZipPath extends Path {
}
@Override
public ZipPath resolve(String other) {
return resolve(getFileSystem().getPath(other));
public Path resolveSibling(Path other) {
if (other == null)
throw new NullPointerException();
Path parent = getParent();
return (parent == null) ? other : parent.resolve(other);
}
@Override
......@@ -332,13 +326,31 @@ public class ZipPath extends Path {
return true;
}
@Override
public ZipPath resolve(String other) {
return resolve(getFileSystem().getPath(other));
}
@Override
public final Path resolveSibling(String other) {
return resolveSibling(getFileSystem().getPath(other));
}
@Override
public final boolean startsWith(String other) {
return startsWith(getFileSystem().getPath(other));
}
@Override
public final boolean endsWith(String other) {
return endsWith(getFileSystem().getPath(other));
}
@Override
public Path normalize() {
byte[] resolved = getResolved();
if (resolved == path) // no change
return this;
if (resolved.length == 0)
return null;
return new ZipPath(zfs, resolved, true);
}
......@@ -548,44 +560,65 @@ public class ZipPath extends Path {
return len1 - len2;
}
@Override
public Path createSymbolicLink(
Path target, FileAttribute<?>... attrs) throws IOException {
throw new UnsupportedOperationException("Not supported.");
public WatchKey register(
WatchService watcher,
WatchEvent.Kind<?>[] events,
WatchEvent.Modifier... modifiers) {
if (watcher == null || events == null || modifiers == null) {
throw new NullPointerException();
}
throw new UnsupportedOperationException();
}
@Override
public Path createLink(
Path existing) throws IOException {
throw new UnsupportedOperationException("Not supported.");
public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) {
return register(watcher, events, new WatchEvent.Modifier[0]);
}
@Override
public Path readSymbolicLink() throws IOException {
throw new UnsupportedOperationException("Not supported.");
public final File toFile() {
throw new UnsupportedOperationException();
}
@Override
public Path createDirectory(FileAttribute<?>... attrs)
throws IOException
{
zfs.createDirectory(getResolvedPath(), attrs);
return this;
public Iterator<Path> iterator() {
return new Iterator<>() {
private int i = 0;
@Override
public boolean hasNext() {
return (i < getNameCount());
}
@Override
public Path next() {
if (i < getNameCount()) {
Path result = getName(i);
i++;
return result;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new ReadOnlyFileSystemException();
}
};
}
public final Path createFile(FileAttribute<?>... attrs)
/////////////////////////////////////////////////////////////////////
void createDirectory(FileAttribute<?>... attrs)
throws IOException
{
OutputStream os = newOutputStream(CREATE_NEW, WRITE);
try {
os.close();
} catch (IOException x) {}
return this;
zfs.createDirectory(getResolvedPath(), attrs);
}
@Override
public InputStream newInputStream(OpenOption... options)
throws IOException {
InputStream newInputStream(OpenOption... options) throws IOException
{
if (options.length > 0) {
for (OpenOption opt : options) {
if (opt != READ)
......@@ -595,49 +628,17 @@ public class ZipPath extends Path {
return zfs.newInputStream(getResolvedPath());
}
private static final DirectoryStream.Filter<Path> acceptAllFilter =
new DirectoryStream.Filter<>() {
@Override public boolean accept(Path entry) { return true; }
};
@Override
public final DirectoryStream<Path> newDirectoryStream() throws IOException {
return newDirectoryStream(acceptAllFilter);
}
@Override
public DirectoryStream<Path> newDirectoryStream(Filter<? super Path> filter)
DirectoryStream<Path> newDirectoryStream(Filter<? super Path> filter)
throws IOException
{
return new ZipDirectoryStream(this, filter);
}
@Override
public final DirectoryStream<Path> newDirectoryStream(String glob)
throws IOException
{
// avoid creating a matcher if all entries are required.
if (glob.equals("*"))
return newDirectoryStream();
// create a matcher and return a filter that uses it.
final PathMatcher matcher = getFileSystem().getPathMatcher("glob:" + glob);
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<>() {
@Override
public boolean accept(Path entry) {
return matcher.matches(entry.getName());
}
};
return newDirectoryStream(filter);
}
@Override
public final void delete() throws IOException {
void delete() throws IOException {
zfs.deleteFile(getResolvedPath(), true);
}
@Override
public final void deleteIfExists() throws IOException {
void deleteIfExists() throws IOException {
zfs.deleteFile(getResolvedPath(), false);
}
......@@ -649,18 +650,7 @@ public class ZipPath extends Path {
return zfas;
}
@Override
@SuppressWarnings("unchecked")
public <V extends FileAttributeView> V getFileAttributeView(Class<V> type,
LinkOption... options)
{
return (V)ZipFileAttributeView.get(this, type);
}
@Override
public void setAttribute(String attribute,
Object value,
LinkOption... options)
void setAttribute(String attribute, Object value, LinkOption... options)
throws IOException
{
String type = null;
......@@ -685,107 +675,48 @@ public class ZipPath extends Path {
zfs.setTimes(getResolvedPath(), mtime, atime, ctime);
}
private Object getAttributesImpl(String attribute, boolean domap)
Map<String, Object> readAttributes(String attributes, LinkOption... options)
throws IOException
{
String view = null;
String attr = null;
int colonPos = attribute.indexOf(':');
String attrs = null;
int colonPos = attributes.indexOf(':');
if (colonPos == -1) {
view = "basic";
attr = attribute;
attrs = attributes;
} else {
view = attribute.substring(0, colonPos++);
attr = attribute.substring(colonPos);
view = attributes.substring(0, colonPos++);
attrs = attributes.substring(colonPos);
}
ZipFileAttributeView zfv = ZipFileAttributeView.get(this, view);
if (zfv == null) {
throw new UnsupportedOperationException("view not supported");
}
return zfv.getAttribute(attr, domap);
}
@Override
public Object getAttribute(String attribute, LinkOption... options)
throws IOException
{
return getAttributesImpl(attribute, false);
}
@Override
public Map<String,?> readAttributes(String attribute, LinkOption... options)
throws IOException
{
return (Map<String, ?>)getAttributesImpl(attribute, true);
return zfv.readAttributes(attrs);
}
@Override
public FileStore getFileStore() throws IOException {
FileStore getFileStore() throws IOException {
// each ZipFileSystem only has one root (as requested for now)
if (exists())
return zfs.getFileStore(this);
throw new NoSuchFileException(zfs.getString(path));
}
@Override
public boolean isSameFile(Path other) throws IOException {
boolean isSameFile(Path other) throws IOException {
if (this.equals(other))
return true;
if (other == null ||
this.getFileSystem() != other.getFileSystem())
return false;
this.checkAccess();
other.checkAccess();
((ZipPath)other).checkAccess();
return Arrays.equals(this.getResolvedPath(),
((ZipPath)other).getResolvedPath());
}
public WatchKey register(
WatchService watcher,
WatchEvent.Kind<?>[] events,
WatchEvent.Modifier... modifiers) {
if (watcher == null || events == null || modifiers == null) {
throw new NullPointerException();
}
throw new UnsupportedOperationException();
}
@Override
public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) {
return register(watcher, events, new WatchEvent.Modifier[0]);
}
@Override
public Iterator<Path> iterator() {
return new Iterator<>() {
private int i = 0;
@Override
public boolean hasNext() {
return (i < getNameCount());
}
@Override
public Path next() {
if (i < getNameCount()) {
Path result = getName(i);
i++;
return result;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new ReadOnlyFileSystemException();
}
};
}
@Override
public SeekableByteChannel newByteChannel(Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
SeekableByteChannel newByteChannel(Set<? extends OpenOption> options,
FileAttribute<?>... attrs)
throws IOException
{
return zfs.newByteChannel(getResolvedPath(), options, attrs);
......@@ -799,16 +730,7 @@ public class ZipPath extends Path {
return zfs.newFileChannel(getResolvedPath(), options, attrs);
}
@Override
public SeekableByteChannel newByteChannel(OpenOption... options)
throws IOException {
Set<OpenOption> set = new HashSet<>(options.length);
Collections.addAll(set, options);
return newByteChannel(set);
}
@Override
public void checkAccess(AccessMode... modes) throws IOException {
void checkAccess(AccessMode... modes) throws IOException {
boolean w = false;
boolean x = false;
for (AccessMode mode : modes) {
......@@ -834,11 +756,9 @@ public class ZipPath extends Path {
}
if (x)
throw new AccessDeniedException(toString());
}
@Override
public boolean exists() {
boolean exists() {
if (path.length == 1 && path[0] == '/')
return true;
try {
......@@ -847,15 +767,7 @@ public class ZipPath extends Path {
return false;
}
@Override
public boolean notExists() {
return !exists();
}
@Override
public OutputStream newOutputStream(OpenOption... options)
throws IOException
OutputStream newOutputStream(OpenOption... options) throws IOException
{
if (options.length == 0)
return zfs.newOutputStream(getResolvedPath(),
......@@ -863,42 +775,32 @@ public class ZipPath extends Path {
return zfs.newOutputStream(getResolvedPath(), options);
}
@Override
public Path moveTo(Path target, CopyOption... options)
void move(ZipPath target, CopyOption... options)
throws IOException
{
if (this.zfs.provider() == target.getFileSystem().provider() &&
this.zfs.getZipFile().isSameFile(((ZipPath)target).zfs.getZipFile()))
if (Files.isSameFile(this.zfs.getZipFile(), target.zfs.getZipFile()))
{
zfs.copyFile(true,
getResolvedPath(),
((ZipPath)target).getResolvedPath(),
getResolvedPath(), target.getResolvedPath(),
options);
} else {
copyToTarget(target, options);
delete();
}
return target;
}
@Override
public Path copyTo(Path target, CopyOption... options)
void copy(ZipPath target, CopyOption... options)
throws IOException
{
if (this.zfs.provider() == target.getFileSystem().provider() &&
this.zfs.getZipFile().isSameFile(((ZipPath)target).zfs.getZipFile()))
{
if (Files.isSameFile(this.zfs.getZipFile(), target.zfs.getZipFile()))
zfs.copyFile(false,
getResolvedPath(),
((ZipPath)target).getResolvedPath(),
getResolvedPath(), target.getResolvedPath(),
options);
} else {
else
copyToTarget(target, options);
}
return target;
}
private void copyToTarget(Path target, CopyOption... options)
private void copyToTarget(ZipPath target, CopyOption... options)
throws IOException
{
boolean replaceExisting = false;
......@@ -948,7 +850,7 @@ public class ZipPath extends Path {
}
if (copyAttrs) {
BasicFileAttributeView view =
target.getFileAttributeView(BasicFileAttributeView.class);
ZipFileAttributeView.get(target, BasicFileAttributeView.class);
try {
view.setTimes(zfas.lastModifiedTime(),
zfas.lastAccessTime(),
......
此差异已折叠。
......@@ -48,9 +48,9 @@ public class Basic {
if (!found)
throw new RuntimeException("'jar' provider not installed");
// Test: FileSystems#newFileSystem(FileRef)
// Test: FileSystems#newFileSystem(Path)
Map<String,?> env = new HashMap<String,Object>();
FileSystems.newFileSystem(zipfile, env, null).close();
FileSystems.newFileSystem(zipfile, null).close();
// Test: FileSystems#newFileSystem(URI)
URI uri = new URI("jar", zipfile.toUri().toString(), null);
......@@ -69,14 +69,11 @@ public class Basic {
// Test: DirectoryStream
found = false;
DirectoryStream<Path> stream = fs.getPath("/").newDirectoryStream();
try {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(fs.getPath("/"))) {
for (Path entry: stream) {
found = entry.toString().equals("/META-INF/");
if (found) break;
}
} finally {
stream.close();
}
if (!found)
......@@ -84,21 +81,21 @@ public class Basic {
// Test: copy file from zip file to current (scratch) directory
Path source = fs.getPath("/META-INF/services/java.nio.file.spi.FileSystemProvider");
if (source.exists()) {
Path target = Paths.get(source.getName().toString());
source.copyTo(target, StandardCopyOption.REPLACE_EXISTING);
if (Files.exists(source)) {
Path target = Paths.get(source.getFileName().toString());
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
try {
long s1 = Attributes.readBasicFileAttributes(source).size();
long s2 = Attributes.readBasicFileAttributes(target).size();
long s1 = Files.readAttributes(source, BasicFileAttributes.class).size();
long s2 = Files.readAttributes(target, BasicFileAttributes.class).size();
if (s2 != s1)
throw new RuntimeException("target size != source size");
} finally {
target.delete();
Files.delete(target);
}
}
// Test: FileStore
FileStore store = fs.getPath("/").getFileStore();
FileStore store = Files.getFileStore(fs.getPath("/"));
if (!store.supportsFileAttributeView("basic"))
throw new RuntimeException("BasicFileAttributeView should be supported");
......@@ -107,7 +104,7 @@ public class Basic {
if (fs.isOpen())
throw new RuntimeException("FileSystem should be closed");
try {
fs.getPath("/missing").checkAccess(AccessMode.READ);
fs.provider().checkAccess(fs.getPath("/missing"), AccessMode.READ);
} catch (ClosedFileSystemException x) { }
}
......@@ -125,9 +122,9 @@ public class Basic {
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs)
{
if (dir.getName() != null) {
if (dir.getFileName() != null) {
indent();
System.out.println(dir.getName() + "/");
System.out.println(dir.getFileName() + "/");
indent++;
}
return FileVisitResult.CONTINUE;
......@@ -138,7 +135,7 @@ public class Basic {
BasicFileAttributes attrs)
{
indent();
System.out.print(file.getName());
System.out.print(file.getFileName());
if (attrs.isRegularFile())
System.out.format(" (%d)", attrs.size());
System.out.println();
......@@ -151,7 +148,7 @@ public class Basic {
{
if (exc != null)
super.postVisitDirectory(dir, exc);
if (dir.getName() != null)
if (dir.getFileName() != null)
indent--;
return FileVisitResult.CONTINUE;
}
......
......@@ -100,7 +100,7 @@ public class PathOps {
PathOps name(String expected) {
out.println("check name");
checkPath();
check(path.getName(), expected);
check(path.getFileName(), expected);
return this;
}
......@@ -197,7 +197,7 @@ public class PathOps {
try {
out.println("check two paths are same");
checkPath();
check(path.isSameFile(test(target).path()), true);
check(Files.isSameFile(path, test(target).path()), true);
} catch (IOException ioe) {
fail();
}
......@@ -320,7 +320,7 @@ public class PathOps {
// relativize
test("/a/b/c")
.relativize("/a/b/c", null)
.relativize("/a/b/c", "")
.relativize("/a/b/c/d/e", "d/e")
.relativize("/a/x", "../../x");
......@@ -332,7 +332,7 @@ public class PathOps {
test("/foo")
.normalize("/foo");
test(".")
.normalize(null);
.normalize("");
test("..")
.normalize("..");
test("/..")
......@@ -344,7 +344,7 @@ public class PathOps {
test("./foo")
.normalize("foo");
test("foo/..")
.normalize(null);
.normalize("");
test("../foo")
.normalize("../foo");
test("../../foo")
......@@ -411,13 +411,13 @@ public class PathOps {
}
try {
path.startsWith(null);
path.startsWith((Path)null);
throw new RuntimeException("NullPointerException not thrown");
} catch (NullPointerException npe) {
}
try {
path.endsWith(null);
path.endsWith((Path)null);
throw new RuntimeException("NullPointerException not thrown");
} catch (NullPointerException npe) {
}
......@@ -427,8 +427,7 @@ public class PathOps {
public static void main(String[] args) throws Throwable {
Path zipfile = Paths.get(args[0]);
Map<String,?> env = new HashMap<String,Object>();
fs = FileSystems.newFileSystem(zipfile, env, null);
fs = FileSystems.newFileSystem(zipfile, null);
npes();
doPathOpTests();
fs.close();
......
......@@ -25,6 +25,7 @@ import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.nio.file.spi.*;
import java.nio.file.attribute.*;
import java.net.*;
import java.util.*;
......@@ -40,15 +41,13 @@ import static java.nio.file.StandardCopyOption.*;
public class ZipFSTester {
public static void main(String[] args) throws Throwable {
FileSystem fs = null;
try {
fs = newZipFileSystem(Paths.get(args[0]), new HashMap<String, Object>());
try (FileSystem fs = newZipFileSystem(Paths.get(args[0]),
new HashMap<String, Object>()))
{
test0(fs);
test1(fs);
test2(fs); // more tests
} finally {
if (fs != null)
fs.close();
}
}
......@@ -63,10 +62,10 @@ public class ZipFSTester {
}
for (String pname : list) {
Path path = fs.getPath(pname);
if (!path.exists())
if (!Files.exists(path))
throw new RuntimeException("path existence check failed!");
while ((path = path.getParent()) != null) {
if (!path.exists())
if (!Files.exists(path))
throw new RuntimeException("parent existence check failed!");
}
}
......@@ -85,12 +84,22 @@ public class ZipFSTester {
z2zcopy(fs, fs0, "/", 0);
fs0.close(); // sync to file
fs = newZipFileSystem(tmpfsPath, new HashMap<String, Object>());
try {
try (fs = newZipFileSystem(tmpfsPath, new HashMap<String, Object>())) {
FileSystemProvider provider = fs.provider();
// newFileSystem(path...) should not throw exception
try (FileSystem fsPath = provider.newFileSystem(tmpfsPath, new HashMap<String, Object>())){}
try (FileSystem fsUri = provider.newFileSystem(
new URI("jar", tmpfsPath.toUri().toString(), null),
new HashMap<String, Object>()))
{
throw new RuntimeException("newFileSystem(uri...) does not throw exception");
} catch (FileSystemAlreadyExistsException fsaee) {}
// prepare a src
Path src = getTempPath();
String tmpName = src.toString();
OutputStream os = src.newOutputStream();
OutputStream os = Files.newOutputStream(src);
byte[] bits = new byte[12345];
rdm.nextBytes(bits);
os.write(bits);
......@@ -98,37 +107,37 @@ public class ZipFSTester {
// copyin
Path dst = getPathWithParents(fs, tmpName);
src.copyTo(dst);
Files.copy(src, dst);
checkEqual(src, dst);
// copy
Path dst2 = getPathWithParents(fs, "/xyz" + rdm.nextInt(100) +
"/efg" + rdm.nextInt(100) + "/foo.class");
dst.copyTo(dst2);
Files.copy(dst, dst2);
//dst.moveTo(dst2);
checkEqual(src, dst2);
// delete
dst.delete();
if (dst.exists())
Files.delete(dst);
if (Files.exists(dst))
throw new RuntimeException("Failed!");
// moveout
Path dst3 = Paths.get(tmpName + "_Tmp");
dst2.moveTo(dst3);
Files.move(dst2, dst3);
checkEqual(src, dst3);
// delete
if (dst2.exists())
if (Files.exists(dst2))
throw new RuntimeException("Failed!");
dst3.delete();
if (dst3.exists())
Files.delete(dst3);
if (Files.exists(dst3))
throw new RuntimeException("Failed!");
// newInputStream on dir
Path parent = dst2.getParent();
try {
parent.newInputStream();
Files.newInputStream(parent);
throw new RuntimeException("Failed");
} catch (FileSystemException e) {
e.printStackTrace(); // expected fse
......@@ -147,17 +156,15 @@ public class ZipFSTester {
Path tmp = Paths.get(tmpName + "_Tmp");
fchCopy(dst, tmp); // out
checkEqual(src, tmp);
tmp.delete();
Files.delete(tmp);
// test channels
channel(fs, dst);
dst.delete();
src.delete();
Files.delete(dst);
Files.delete(src);
} finally {
if (fs != null)
fs.close();
if (tmpfsPath.exists())
tmpfsPath.delete();
if (Files.exists(tmpfsPath))
Files.delete(tmpfsPath);
}
}
......@@ -242,7 +249,7 @@ public class ZipFSTester {
while (itr.hasNext()) {
String path = itr.next();
try {
if (fs2.getPath(path).exists()) {
if (Files.exists(fs2.getPath(path))) {
z2zmove(fs2, fs3, path);
itr.remove();
}
......@@ -296,15 +303,16 @@ public class ZipFSTester {
fs4.close();
System.out.printf("failed=%d%n", failed);
fs1Path.delete();
fs2Path.delete();
fs3Path.delete();
Files.delete(fs1Path);
Files.delete(fs2Path);
Files.delete(fs3Path);
}
private static FileSystem newZipFileSystem(Path path, Map<String, ?> env)
throws IOException
throws Exception
{
return FileSystems.newFileSystem(path, env, null);
return FileSystems.newFileSystem(
new URI("jar", path.toUri().toString(), null), env, null);
}
private static Path getTempPath() throws IOException
......@@ -317,11 +325,11 @@ public class ZipFSTester {
private static void list(Path path, List<String> files, List<String> dirs )
throws IOException
{
if (Attributes.readBasicFileAttributes(path).isDirectory()) {
DirectoryStream<Path> ds = path.newDirectoryStream();
for (Path child : ds)
list(child, files, dirs);
ds.close();
if (Files.isDirectory(path)) {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
for (Path child : ds)
list(child, files, dirs);
}
dirs.add(path.toString());
} else {
files.add(path.toString());
......@@ -335,26 +343,26 @@ public class ZipFSTester {
Path srcPath = src.getPath(path);
Path dstPath = dst.getPath(path);
if (Boolean.TRUE.equals(srcPath.getAttribute("isDirectory"))) {
if (!dstPath.exists()) {
if (Files.isDirectory(srcPath)) {
if (!Files.exists(dstPath)) {
try {
mkdirs(dstPath);
} catch (FileAlreadyExistsException x) {}
}
DirectoryStream<Path> ds = srcPath.newDirectoryStream();
for (Path child : ds) {
z2zcopy(src, dst,
path + (path.endsWith("/")?"":"/") + child.getName(),
method);
try (DirectoryStream<Path> ds = Files.newDirectoryStream(srcPath)) {
for (Path child : ds) {
z2zcopy(src, dst,
path + (path.endsWith("/")?"":"/") + child.getFileName(),
method);
}
}
ds.close();
} else {
try {
if (dstPath.exists())
if (Files.exists(dstPath))
return;
switch (method) {
case 0:
srcPath.copyTo(dstPath);
Files.copy(srcPath, dstPath);
break;
case 1:
chCopy(srcPath, dstPath);
......@@ -374,21 +382,21 @@ public class ZipFSTester {
Path srcPath = src.getPath(path);
Path dstPath = dst.getPath(path);
if (Boolean.TRUE.equals(srcPath.getAttribute("isDirectory"))) {
if (!dstPath.exists())
if (Files.isDirectory(srcPath)) {
if (!Files.exists(dstPath))
mkdirs(dstPath);
DirectoryStream<Path> ds = srcPath.newDirectoryStream();
for (Path child : ds) {
z2zmove(src, dst,
path + (path.endsWith("/")?"":"/") + child.getName());
try (DirectoryStream<Path> ds = Files.newDirectoryStream(srcPath)) {
for (Path child : ds) {
z2zmove(src, dst,
path + (path.endsWith("/")?"":"/") + child.getFileName());
}
}
ds.close();
} else {
//System.out.println("moving..." + path);
Path parent = dstPath.getParent();
if (parent != null && parent.notExists())
if (parent != null && Files.notExists(parent))
mkdirs(parent);
srcPath.moveTo(dstPath);
Files.move(srcPath, dstPath);
}
}
......@@ -409,7 +417,7 @@ public class ZipFSTester {
BasicFileAttributes attrs)
{
indent();
System.out.printf("%s%n", file.getName().toString());
System.out.printf("%s%n", file.getFileName().toString());
return FileVisitResult.CONTINUE;
}
......@@ -435,20 +443,20 @@ public class ZipFSTester {
}
private static void mkdirs(Path path) throws IOException {
if (path.exists())
if (Files.exists(path))
return;
path = path.toAbsolutePath();
Path parent = path.getParent();
if (parent != null) {
if (parent.notExists())
if (Files.notExists(parent))
mkdirs(parent);
}
path.createDirectory();
Files.createDirectory(path);
}
private static void rmdirs(Path path) throws IOException {
while (path != null && path.getNameCount() != 0) {
path.delete();
Files.delete(path);
path = path.getParent();
}
}
......@@ -460,12 +468,11 @@ public class ZipFSTester {
// src.toString(), dst.toString());
//streams
InputStream isSrc = src.newInputStream();
InputStream isDst = dst.newInputStream();
byte[] bufSrc = new byte[8192];
byte[] bufDst = new byte[8192];
try {
try (InputStream isSrc = Files.newInputStream(src);
InputStream isDst = Files.newInputStream(dst))
{
int nSrc = 0;
while ((nSrc = isSrc.read(bufSrc)) != -1) {
int nDst = 0;
......@@ -487,24 +494,21 @@ public class ZipFSTester {
nSrc--;
}
}
} finally {
isSrc.close();
isDst.close();
}
// channels
SeekableByteChannel chSrc = src.newByteChannel();
SeekableByteChannel chDst = dst.newByteChannel();
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);
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);
try {
int nSrc = 0;
while ((nSrc = chSrc.read(bbSrc)) != -1) {
int nDst = chDst.read(bbDst);
......@@ -526,9 +530,6 @@ public class ZipFSTester {
}
} catch (IOException x) {
x.printStackTrace();
} finally {
chSrc.close();
chDst.close();
}
}
......@@ -540,23 +541,19 @@ public class ZipFSTester {
openwrite.add(CREATE_NEW);
openwrite.add(WRITE);
FileChannel srcFc = src.getFileSystem()
.provider()
.newFileChannel(src, read);
FileChannel dstFc = dst.getFileSystem()
.provider()
.newFileChannel(dst, openwrite);
try {
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();
}
} finally {
srcFc.close();
dstFc.close();
}
}
......@@ -568,35 +565,29 @@ public class ZipFSTester {
openwrite.add(CREATE_NEW);
openwrite.add(WRITE);
SeekableByteChannel srcCh = src.newByteChannel(read);
SeekableByteChannel dstCh = dst.newByteChannel(openwrite);
try (SeekableByteChannel srcCh = Files.newByteChannel(src, read);
SeekableByteChannel dstCh = Files.newByteChannel(dst, openwrite))
{
try {
ByteBuffer bb = ByteBuffer.allocate(8192);
while (srcCh.read(bb) >= 0) {
bb.flip();
dstCh.write(bb);
bb.clear();
}
} finally {
srcCh.close();
dstCh.close();
}
}
private static void streamCopy(Path src, Path dst) throws IOException
{
InputStream isSrc = src.newInputStream();
OutputStream osDst = dst.newOutputStream();
byte[] buf = new byte[8192];
try {
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);
}
} finally {
isSrc.close();
osDst.close();
}
}
......@@ -604,31 +595,35 @@ public class ZipFSTester {
throws Exception
{
System.out.println("test ByteChannel...");
SeekableByteChannel sbc = path.newByteChannel();
Set<OpenOption> read = new HashSet<>();
read.add(READ);
System.out.printf(" sbc[0]: pos=%d, size=%d%n", sbc.position(), sbc.size());
ByteBuffer bb = ByteBuffer.allocate((int)sbc.size());
int n = sbc.read(bb);
System.out.printf(" sbc[1]: read=%d, pos=%d, size=%d%n",
n, sbc.position(), sbc.size());
ByteBuffer bb2 = ByteBuffer.allocate((int)sbc.size());
int n = 0;
ByteBuffer bb = null;
ByteBuffer bb2 = null;
int N = 120;
sbc.close();
try (SeekableByteChannel sbc = Files.newByteChannel(path)) {
System.out.printf(" sbc[0]: pos=%d, size=%d%n", sbc.position(), sbc.size());
bb = ByteBuffer.allocate((int)sbc.size());
n = sbc.read(bb);
System.out.printf(" sbc[1]: read=%d, pos=%d, size=%d%n",
n, sbc.position(), sbc.size());
bb2 = ByteBuffer.allocate((int)sbc.size());
}
// sbc.position(pos) is not supported in current version
// try the FileChannel
sbc = fs.provider().newFileChannel(path, read);
sbc.position(N);
System.out.printf(" sbc[2]: pos=%d, size=%d%n",
sbc.position(), sbc.size());
bb2.limit(100);
n = sbc.read(bb2);
System.out.printf(" sbc[3]: read=%d, pos=%d, size=%d%n",
n, sbc.position(), sbc.size());
System.out.printf(" sbc[4]: bb[%d]=%d, bb1[0]=%d%n",
N, bb.get(N) & 0xff, bb2.get(0) & 0xff);
sbc.close();
try (SeekableByteChannel sbc = fs.provider().newFileChannel(path, read)) {
sbc.position(N);
System.out.printf(" sbc[2]: pos=%d, size=%d%n",
sbc.position(), sbc.size());
bb2.limit(100);
n = sbc.read(bb2);
System.out.printf(" sbc[3]: read=%d, pos=%d, size=%d%n",
n, sbc.position(), sbc.size());
System.out.printf(" sbc[4]: bb[%d]=%d, bb1[0]=%d%n",
N, bb.get(N) & 0xff, bb2.get(0) & 0xff);
}
}
// create parents if does not exist
......@@ -637,7 +632,7 @@ public class ZipFSTester {
{
Path path = fs.getPath(name);
Path parent = path.getParent();
if (parent != null && parent.notExists())
if (parent != null && Files.notExists(parent))
mkdirs(parent);
return path;
}
......
......@@ -21,8 +21,7 @@
# questions.
#
# @test
# @bug 6990846 7009092 7009085
# @ignore Until zipfs updated (7015391)
# @bug 6990846 7009092 7009085 7015391 7014948
# @summary Test ZipFileSystem demo
# @build Basic PathOps ZipFSTester
# @run shell basic.sh
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册