下面列出了java.nio.file.FileSystem#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Lists all children resources.
*
* @param parent the root path represented in {@link URI} format
* @param consumer consumer for children resources
* @throws java.io.IOException if any i/o error occur
* @throws ProviderNotFoundException if a provider supporting the URI scheme is not installed
*/
public static void listResources(URI parent, Consumer<Path> consumer) throws IOException {
FileSystem fileSystem = null;
try {
if (!"file".equals(parent.getScheme())) {
try {
fileSystem = FileSystems.newFileSystem(parent, Collections.emptyMap());
} catch (FileSystemAlreadyExistsException ignore) {
}
}
Path root = Paths.get(parent);
Files.list(root).forEach(consumer);
} finally {
// close FS only if only it has been initialized here
if (fileSystem != null) {
fileSystem.close();
}
}
}
public void validate(){
synchronized (metaData){
if(validate!=Validate.NOT_VALIDATED)return;
}
String uploadderClNm = metaData.getImplementation("neembuu.uploader.interfaces.Uploader");
String accountClzzNm = metaData.getImplementation("neembuu.uploader.interfaces.Account");
try{
final FileSystem zipfs = FileSystems.newFileSystem(metaData.getModuleFile(),null);
close = new Close() { @Override public void close()throws Exception { zipfs.close(); } };
ZipClassLoader zcl = new ZipClassLoader(zipfs);
uploader = zcl.loadClass(uploadderClNm);
account = zcl.loadClass(accountClzzNm);
}catch(Exception a){
a.printStackTrace();
validate = Validate.CORRUPT;
try {close(); }catch(Exception a2){a2.printStackTrace();}
return;
}
validate = Validate.VALIDATED;
}
public static void main(String[] args)
throws IOException, URISyntaxException {
String os = System.getProperty("os.name");
FileSystem fs = FileSystems.getDefault();
// close should throw UOE
try {
fs.close();
throw new RuntimeException("UnsupportedOperationException expected");
} catch (UnsupportedOperationException e) { }
check(fs.isOpen(), "should be open");
check(!fs.isReadOnly(), "should provide read-write access");
check(fs.provider().getScheme().equals("file"),
"should use 'file' scheme");
// sanity check FileStores
checkFileStores(fs);
// sanity check supportedFileAttributeViews
checkSupported(fs, "basic");
if (os.equals("SunOS"))
checkSupported(fs, "posix", "unix", "owner", "acl", "user");
if (os.equals("Linux"))
checkSupported(fs, "posix", "unix", "owner", "dos", "user");
if (os.contains("OS X"))
checkSupported(fs, "posix", "unix", "owner");
if (os.equals("Windows"))
checkSupported(fs, "owner", "dos", "acl", "user");
}
public static void main(String[] args)
throws IOException, URISyntaxException {
String os = System.getProperty("os.name");
FileSystem fs = FileSystems.getDefault();
// close should throw UOE
try {
fs.close();
throw new RuntimeException("UnsupportedOperationException expected");
} catch (UnsupportedOperationException e) { }
check(fs.isOpen(), "should be open");
check(!fs.isReadOnly(), "should provide read-write access");
check(fs.provider().getScheme().equals("file"),
"should use 'file' scheme");
// sanity check FileStores
checkFileStores(fs);
// sanity check supportedFileAttributeViews
checkSupported(fs, "basic");
if (os.equals("SunOS"))
checkSupported(fs, "posix", "unix", "owner", "acl", "user");
if (os.equals("Linux"))
checkSupported(fs, "posix", "unix", "owner", "dos", "user");
if (os.contains("OS X"))
checkSupported(fs, "posix", "unix", "owner");
if (os.equals("Windows"))
checkSupported(fs, "owner", "dos", "acl", "user");
}
public boolean renameZipEntries(String zipFile, String[] entryNames, String[] newEntryNames) throws Exception {
if (logger.isDebugEnabled()) {
StringBuilder sb = new StringBuilder("--> renameZipEntries()");
sb.append(", zipFile=");
sb.append(zipFile);
sb.append(", entryNames=[");
for (int i = 0; i < entryNames.length; i++) {
if (i > 0) sb.append(",");
sb.append(entryNames[i]);
}
sb.append("], newEntryNames=[");
for (int i = 0; i < newEntryNames.length; i++) {
if (i > 0) sb.append(",");
sb.append(newEntryNames[i]);
}
sb.append("]");
logger.debug(sb.toString());
}
boolean ret = false;
if (entryNames.length != newEntryNames.length)
throw new Exception("renameZipEntries entryNames and newEntryNames length should be same");
HashMap<String, String> props = new HashMap<String, String>();
props.put("create", "false");
URI zipDisk = URI.create("jar:" + new File(zipFile).toURI());
FileSystem zipfs = FileSystems.newFileSystem(zipDisk, props);
Path pathInZipfile, renamedZipEntry;
for (int i = 0; i < entryNames.length; i++) {
pathInZipfile = zipfs.getPath(entryNames[i]);
renamedZipEntry = zipfs.getPath(newEntryNames[i]);
Files.move(pathInZipfile, renamedZipEntry, StandardCopyOption.ATOMIC_MOVE);
}
zipfs.close();
ret = true;
logger.debug("<-- renameZipEntries()");
return ret;
}
private void maybeCloseFileSystem() {
FileSystem outputFileSystem = options.getOutput().getFileSystem();
if (outputFileSystem.getClass().getCanonicalName().equals("com.sun.nio.zipfs.ZipFileSystem")
|| outputFileSystem.getClass().getCanonicalName().equals("jdk.nio.zipfs.ZipFileSystem")) {
try {
outputFileSystem.close();
} catch (IOException e) {
problems.fatal(FatalError.CANNOT_CLOSE_ZIP, e.getMessage());
}
}
}
public static void main(String[] args)
throws IOException, URISyntaxException {
String os = System.getProperty("os.name");
FileSystem fs = FileSystems.getDefault();
// close should throw UOE
try {
fs.close();
throw new RuntimeException("UnsupportedOperationException expected");
} catch (UnsupportedOperationException e) { }
check(fs.isOpen(), "should be open");
check(!fs.isReadOnly(), "should provide read-write access");
check(fs.provider().getScheme().equals("file"),
"should use 'file' scheme");
// sanity check FileStores
checkFileStores(fs);
// sanity check supportedFileAttributeViews
checkSupported(fs, "basic");
if (os.equals("SunOS"))
checkSupported(fs, "posix", "unix", "owner", "acl", "user");
if (os.equals("Linux"))
checkSupported(fs, "posix", "unix", "owner", "dos", "user");
if (os.contains("OS X"))
checkSupported(fs, "posix", "unix", "owner");
if (os.equals("Windows"))
checkSupported(fs, "owner", "dos", "acl", "user");
}
public static void main(String[] args)
throws IOException, URISyntaxException {
String os = System.getProperty("os.name");
FileSystem fs = FileSystems.getDefault();
// close should throw UOE
try {
fs.close();
throw new RuntimeException("UnsupportedOperationException expected");
} catch (UnsupportedOperationException e) { }
check(fs.isOpen(), "should be open");
check(!fs.isReadOnly(), "should provide read-write access");
check(fs.provider().getScheme().equals("file"),
"should use 'file' scheme");
// sanity check FileStores
checkFileStores(fs);
// sanity check supportedFileAttributeViews
checkSupported(fs, "basic");
if (os.equals("SunOS"))
checkSupported(fs, "posix", "unix", "owner", "acl", "user");
if (os.equals("Linux"))
checkSupported(fs, "posix", "unix", "owner", "dos", "user");
if (os.contains("OS X"))
checkSupported(fs, "posix", "unix", "owner");
if (os.equals("Windows"))
checkSupported(fs, "owner", "dos", "acl", "user");
// sanity check non-throwing of UnsupportedOperationException by
// FileSystems.newFileSystem(URI, ..)
checkNoUOE();
}
public static void main(String[] args) throws Exception {
String javaHome = args[0];
FileSystem fs = null;
boolean isInstalled = false;
if (args.length == 2) {
fs = createFsByInstalledProvider();
isInstalled = true;
} else {
fs = createFsWithURLClassloader(javaHome);
}
Path mods = fs.getPath("/modules");
try (Stream<Path> stream = Files.walk(mods)) {
stream.forEach(path -> {
path.getFileName();
});
} finally {
try {
fs.close();
} catch (UnsupportedOperationException e) {
if (!isInstalled) {
throw new RuntimeException(
"UnsupportedOperationException is thrown unexpectedly");
}
}
}
}
protected boolean renameZipEntry(String zipFile, String entryName, String newEntryName) throws Exception {
logger.debug("--> renameZipEntry(). zipFile=" + zipFile + ", entryName=" + entryName + ", newEntryName=" + newEntryName);
boolean ret = false;
HashMap<String, String> props = new HashMap<String, String>();
props.put("create", "false");
URI zipDisk = URI.create("jar:" + new File(zipFile).toURI());
FileSystem zipfs = FileSystems.newFileSystem(zipDisk, props);
Path pathInZipfile = zipfs.getPath(entryName);
Path renamedZipEntry = zipfs.getPath(newEntryName);
Files.move(pathInZipfile, renamedZipEntry, StandardCopyOption.ATOMIC_MOVE);
zipfs.close();
ret = true;
logger.debug("<-- renameZipEntry()");
return ret;
}
private ArrayList<URL> getTutorialFiles(final String language) {
final String dir = "tutorials";
final ArrayList<URL> urlList = new ArrayList<>();
final PathMatcher matcher = FileSystems.getDefault().getPathMatcher(getMatcherPattern(language));
try {
final URI uri = Utils.getBARresource(dir).toURI();
FileSystem fileSystem = null;
Path path;
if ("jar".equals(uri.getScheme())) {
fileSystem = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap());
path = fileSystem.getPath(dir);
} else {
path = Paths.get(uri);
}
final Stream<Path> walk = Files.walk(path, 1);
final Iterator<Path> it = walk.iterator();
while (it.hasNext()) {
final Path p = it.next();
if (matcher.matches(p)) {
urlList.add(p.toUri().toURL());
}
}
walk.close();
if (fileSystem != null)
fileSystem.close();
} catch (IOException | URISyntaxException exc) {
return null;
}
return urlList;
}
public static synchronized void close(FileSystem fs) throws IOException {
RefData data = fsRefs.get(fs);
if (data == null || data.refs <= 0) throw new IllegalStateException("fs "+fs+" never opened via FileSystemHandler");
if (--data.refs == 0) {
fsRefs.remove(fs);
if (data.opened) fs.close();
}
}
private static void loadRules(URI uri, List<String> scriptNames,
List<String> scripts) throws IOException {
if (log.isLoggable(Level.FINE)) {
log.fine("Load rules from URI = " + uri);
}
FileSystem fs = null;
String entryName = uri.toString();
int separator = entryName.indexOf(PATH_JAR_SEPARATOR);
if (separator != -1) {
fs = FileSystems.newFileSystem(URI.create(entryName.substring(0, separator)),
Collections.<String, Object>emptyMap());
entryName = entryName.substring(separator + PATH_JAR_SEPARATOR.length());
} else if (entryName.startsWith(FILE_SCHEME)) {
fs = FileSystems.getFileSystem(URI.create(FILE_SCHEME + File.separator));
entryName = entryName.substring(FILE_SCHEME.length());
}
if (fs != null) {
try {
Path rules = fs.getPath(entryName);
Files.walk(rules).filter(f -> f.toString().endsWith(RULE_FILE_EXTENSION)).forEach(f -> {
try {
if (log.isLoggable(Level.FINE)) {
log.fine("Loading rules: " + f.toString());
}
scripts.add(new String(Files.readAllBytes(f)));
scriptNames.add(f.toString());
} catch (IOException ioe) {
log.log(Level.SEVERE, "Failed to load rule file: " + f.toString(), ioe);
}
});
} finally {
// If created filesystem, then we need to close it
if (separator != -1) {
fs.close();
}
}
}
}
@Override
public void close() throws IOException {
for (FileSystem fs: fileSystems.values())
fs.close();
}
@Override
public void close() throws IOException {
for (FileSystem fs: fileSystems.values())
fs.close();
}
@Override
public void close() throws IOException {
for (FileSystem fs : filesystems.values()) {
fs.close();
}
}
@Override
public void close() throws IOException {
for (FileSystem fs: fileSystems.values())
fs.close();
}
@Test(expectedExceptions = UnsupportedOperationException.class)
public void testCloseFileSystem() throws Exception {
FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
fs.close(); // should throw UOE
}
@Override
public void close() throws IOException {
for (FileSystem fs: fileSystems.values())
fs.close();
}
/**
* called for compiled input when a compiler is available and don't have name collision
* if the container is a PEAR or a Jar
* Updates a copy of the Pear or Jar
* @param container
*/
private void postProcessPearOrJar(Container container) {
Path outDir = Paths.get(outputDirectory,
container.isJar ? "jars" : "pears",
Integer.toString(container.id));
withIOX(() -> Files.createDirectories(outDir));
si(psb).append("Replacing .class files in copy of ").append(container.rootOrig);
flush(psb);
try {
// copy the pear or jar so we don't change the original
Path lastPartOfPath = container.rootOrig.getFileName();
if (null == lastPartOfPath) throw new RuntimeException("Internal Error");
Path pearOrJarCopy = Paths.get(outputDirectory,
container.isJar ? "jars" : "pears",
Integer.toString(container.id),
lastPartOfPath.toString());
Files.copy(container.rootOrig, pearOrJarCopy);
// put up a file system on the pear or jar
FileSystem pfs = FileSystems.newFileSystem(pearOrJarCopy, (ClassLoader) null);
// replace the .class files in this PEAR or Jar with corresponding v3 ones
indent[0] += 2;
String[] previousSkip = {""};
container.v3CompiledPathAndContainerItemPath.forEach(c_p -> {
if (Files.exists(c_p.v3CompiledPath)) {
withIOX(() -> Files.copy(c_p.v3CompiledPath, pfs.getPath(c_p.pathInContainer), StandardCopyOption.REPLACE_EXISTING));
reportPearOrJarClassReplace(pearOrJarCopy.toString(), c_p.v3CompiledPath.toString(), container);
} else {
String pstr = c_p.v3CompiledPath.toString();
String pstr2 = pstr;
if (previousSkip[0] != "") {
int cmn = findFirstCharDifferent(previousSkip[0], pstr);
pstr2 = cmn > 5
? ("..." + pstr.substring(cmn))
: pstr;
}
previousSkip[0] = pstr;
si(psb).append("Skipping replacing ").append(pstr2)
.append(" because it could not be found, perhaps due to compile errors.");
flush(psb);
}
});
indent[0] -= 2;
// for (CommonConverted cc : container.convertedItems) {
// Map<Container, Path> v3ccs = cc.v3CompiledResultPaths;
// v3ccs.forEach((v3ccc, v3cc_path) ->
// {
// if (v3ccc == container) {
// String path_in_v3_classes = cc.v3CompiledResultPaths.get(container).toString();
//
// withIOX(() -> Files.copy(v3cc_path, pfs.getPath(path_in_v3_classes)));
// reportPearOrJarClassReplace(pearOrJarCopy.toString(), path_in_v3_classes, container);
// }
// });
// }
pfs.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}