java.nio.file.FileSystems#getFileSystem ( )源码实例Demo

下面列出了java.nio.file.FileSystems#getFileSystem ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: openjdk-jdk9   文件: Basic.java
/**
 * Test the URI of every file in the jrt file system
 */
@Test
public void testToAndFromUri() throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path top = fs.getPath("/");
    try (Stream<Path> stream = Files.walk(top)) {
        stream.forEach(path -> {
            URI u = path.toUri();
            assertTrue(u.getScheme().equalsIgnoreCase("jrt"));
            assertFalse(u.isOpaque());
            assertTrue(u.getAuthority() == null);
            assertEquals(u.getPath(), path.toAbsolutePath().toString());
            Path p = Paths.get(u);
            assertEquals(p, path);
        });
    }
}
 
源代码2 项目: vind   文件: FileSystemUtils.java
/**
 * Convert a local URL (file:// or jar:// protocol) to a {@link Path}
 * @param resource the URL resource
 * @return the Path
 * @throws URISyntaxException
 * @throws IOException
 */
public static Path toPath(URL resource) throws IOException, URISyntaxException {
    if (resource == null) return null;

    final String protocol = resource.getProtocol();
    if ("file".equals(protocol)) {
        return Paths.get(resource.toURI());
    } else if ("jar".equals(protocol)) {
        final String s = resource.toString();
        final int separator = s.indexOf("!/");
        final String entryName = s.substring(separator + 2);
        final URI fileURI = URI.create(s.substring(0, separator));

        final FileSystem fileSystem;
        synchronized (jarFileSystems) {
            if (jarFileSystems.add(fileURI)) {
                fileSystem = FileSystems.newFileSystem(fileURI, Collections.<String, Object>emptyMap());
            } else {
                fileSystem = FileSystems.getFileSystem(fileURI);
            }
        }
        return fileSystem.getPath(entryName);
    } else {
        throw new IOException("Can't read " + resource + ", unknown protocol '" + protocol + "'");
    }
}
 
源代码3 项目: clouditor   文件: FileSystemManager.java
/**
 * Returns a {@link Path} for a given path to a resource.
 *
 * @param resource the resource path
 * @param clazz the class to get the resource from
 * @return a {@link Path} to the resource
 * @throws IOException if the resource was not found or another error occured
 */
public Path getPathForResource(@NotNull String resource, Class<?> clazz) throws IOException {
  URL url = Component.class.getClassLoader().getResource(resource);
  // try directly with class
  if (url == null) {
    // then try with class loader, i.e. for tests
    url = clazz.getResource(resource);
    // if we cannot create an URL, directly try Paths.get()
    if (url == null) {
      return Paths.get(resource);
    }
  }

  URI uri;
  try {
    uri = url.toURI();
  } catch (URISyntaxException ex) {
    throw new IOException(ex);
  }

  /*
   * we need to "register" the specific file system first before we
   * can use Paths.get()
   */
  if ("jar".equals(uri.getScheme())) {
    // this will just register the handler so we can use it for Paths
    try {
      FileSystems.getFileSystem(uri);
    } catch (FileSystemNotFoundException e) {
      jarFileSystem = FileSystems.newFileSystem(uri, Collections.singletonMap("create", true));
      // just to be safe, ignore if we somehow accidentally register it twice
      LOGGER.info("Creating jar file system for URI {}", uri);
    }
  }

  return Paths.get(uri);
}
 
源代码4 项目: openjdk-jdk9   文件: Basic.java
@Test(dataProvider = "topLevelPkgDirs")
public void testNotExists(String path) throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path dir = fs.getPath(path);

    // package directories should not be there at top level
    assertTrue(Files.notExists(dir));
}
 
源代码5 项目: openjdk-systemtest   文件: TestClassLoading.java
@Test
public void readClassBytes() throws Exception {
	FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
	Path path = fs.getPath("/modules/java.base", "java/lang/Object.class");
	byte[]	jlo	= Files.readAllBytes(path);

	assertNotNull("Can not read bytes of class java/lang/Object.class", jlo);
	assertTrue("Empty byte array returned for java/lang/Object.class", jlo.length != 0);
}
 
源代码6 项目: openjdk-jdk9   文件: Basic.java
@Test(dataProvider = "pathGlobPatterns")
public void testGlobPathMatcher(String pattern, String path,
        boolean expectMatch) throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    PathMatcher pm = fs.getPathMatcher("glob:" + pattern);
    Path p = fs.getPath(path);
    assertTrue(Files.exists(p), path);
    assertTrue(!(pm.matches(p) ^ expectMatch),
        p + (expectMatch? " should match " : " should not match ") +
        pattern);
}
 
public static void main(String[] args) throws IOException {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    fs.getFileStores();
    Files.walkFileTree(fs.getPath("/modules/java.desktop"), new SimpleFileVisitor<>() {
        @Override
        public FileVisitResult visitFile(Path file,
                                         BasicFileAttributes attrs) {
            file = file.subpath(2, file.getNameCount());
            String name = file.toString();
            if (name.endsWith(".class")) {
                name = name.substring(0, name.indexOf(".")).replace('/', '.');

                final Class<?> type;
                try {
                    type = Class.forName(name, false, null);
                } catch (Throwable e) {
                    return FileVisitResult.CONTINUE;
                }
                if (type.isAnnotationPresent(SwingContainer.class)) {
                    if (!Container.class.isAssignableFrom(type)) {
                        System.err.println("Wrong annotation for: " + type);
                        throw new RuntimeException();
                    }
                }
            }
            return FileVisitResult.CONTINUE;
        };
    });
}
 
源代码8 项目: openjdk-jdk9   文件: Basic.java
@Test(dataProvider = "packagesLinks")
public void testPackagesLinks(String link) throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path path = fs.getPath(link);
    assertTrue(Files.exists(path), link + " missing");
    assertTrue(Files.isSymbolicLink(path), path + " is not a link");
    path = Files.readSymbolicLink(path);
    assertEquals(path.toString(), "/modules" + link.substring(link.lastIndexOf("/")));
}
 
源代码9 项目: openjdk-jdk9   文件: Basic.java
@Test(dataProvider = "modulesSubDirs")
public void testModulesSubDirs(String module) throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path path = fs.getPath("/modules/" + module);
    assertTrue(Files.isDirectory(path), module + " missing");
    assertTrue(!Files.isSymbolicLink(path), path + " is a link");
}
 
源代码10 项目: openjdk-jdk9   文件: NotificationInfoTest.java
private static Set<String> findStandardMBeansFromRuntime() throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path modules = fs.getPath("/modules");
    return Files.walk(modules)
            .filter(path -> path.toString().endsWith(".class"))
            .map(path -> path.subpath(2, path.getNameCount()))
            .map(Path::toString)
            .map(s -> s.substring(0, s.length() - 6))  // drop .class
            .filter(s -> !s.equals("module-info"))
            .map(s -> s.replace('/', '.'))
            .collect(Collectors.toSet());
}
 
源代码11 项目: openjdk-jdk9   文件: CompressorPluginTest.java
public void test() throws Exception {
    FileSystem fs;
    try {
        fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    } catch (ProviderNotFoundException | FileSystemNotFoundException e) {
        System.err.println("Not an image build, test skipped.");
        return;
    }
    Path javabase = fs.getPath("/modules/java.base");

    checkCompress(gatherResources(javabase), new ZipPlugin(), null,
            new ResourceDecompressorFactory[]{
                new ZipDecompressorFactory()
            });

    ResourcePool classes = gatherClasses(javabase);
    // compress = String sharing
    checkCompress(classes, new StringSharingPlugin(), null,
            new ResourceDecompressorFactory[]{
                new StringSharingDecompressorFactory()});

    // compress level 0 == no compression
    Properties options0 = new Properties();
    options0.setProperty(DefaultCompressPlugin.NAME,
            "0");
    checkCompress(classes, new DefaultCompressPlugin(),
            options0,
            new ResourceDecompressorFactory[]{
            });

    // compress level 1 == String sharing
    Properties options1 = new Properties();
    options1.setProperty(DefaultCompressPlugin.NAME, "1");
    checkCompress(classes, new DefaultCompressPlugin(),
            options1,
            new ResourceDecompressorFactory[]{
                new StringSharingDecompressorFactory()
            });

    // compress level 1 == String sharing + filter
    options1.setProperty(DefaultCompressPlugin.FILTER,
            "**Exception.class");
    options1.setProperty(DefaultCompressPlugin.NAME, "1");
    checkCompress(classes, new DefaultCompressPlugin(),
            options1,
            new ResourceDecompressorFactory[]{
                new StringSharingDecompressorFactory()
            }, Collections.singletonList(".*Exception.class"));

    // compress level 2 == ZIP
    Properties options2 = new Properties();
    options2.setProperty(DefaultCompressPlugin.FILTER,
            "**Exception.class");
    options2.setProperty(DefaultCompressPlugin.NAME, "2");
    checkCompress(classes, new DefaultCompressPlugin(),
            options2,
            new ResourceDecompressorFactory[]{
                new ZipDecompressorFactory()
            }, Collections.singletonList(".*Exception.class"));

    // compress level 2 == ZIP + filter
    options2.setProperty(DefaultCompressPlugin.FILTER,
            "**Exception.class");
    options2.setProperty(DefaultCompressPlugin.NAME, "2");
    checkCompress(classes, new DefaultCompressPlugin(),
            options2,
            new ResourceDecompressorFactory[]{
                new ZipDecompressorFactory(),
            }, Collections.singletonList(".*Exception.class"));
}
 
源代码12 项目: openjdk-systemtest   文件: FileSystemsTest.java
public void testFileSystemIsRegistered() throws URISyntaxException {

		// Check that the expected "memory0" FileSystem is available
		boolean foundInitialProvider = false;

		for (FileSystemProvider provider: FileSystemProvider.installedProviders()) {
			if (provider.getScheme().equalsIgnoreCase("memory0")) {
				foundInitialProvider = true;
			}
		}

		assertTrue("Unable to find intial provider 'memory0'", foundInitialProvider);


		FileSystem memoryFileSystem = FileSystems.getFileSystem(new URI("memory0:///"));
		assertNotNull("Returned memoryFileSystem for 'memory0:///' was null", memoryFileSystem);

		String filename = "bargh";
		assertNotNull("Returned filename for 'memory0:///"+filename+"' was null", memoryFileSystem.getPath(filename));
		
		assertEquals("MemoryFileSystem did not return the expected string representation",
				"/memory/" + filename, memoryFileSystem.getPath(filename).toString());


	}
 
源代码13 项目: openjdk-jdk9   文件: PathOps.java
public static void main(String[] args) throws Throwable {
    fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    npes();
    doPathOpTests();
}
 
源代码14 项目: openjdk-jdk9   文件: ModuleSourceProvider.java
public ModuleSourceProvider() {
    this(FileSystems.getFileSystem(URI.create("jrt:/")), ClassLoader.getSystemClassLoader(), new FileSupport());
}
 
源代码15 项目: openjdk-jdk9   文件: Locations.java
private void initSystemModules() throws IOException {
    if (moduleTable != null)
        return;

    if (systemJavaHome == null) {
        moduleTable = new ModuleTable();
        return;
    }

    if (modules == null) {
        try {
            URI jrtURI = URI.create("jrt:/");
            FileSystem jrtfs;

            if (isCurrentPlatform(systemJavaHome)) {
                jrtfs = FileSystems.getFileSystem(jrtURI);
            } else {
                try {
                    Map<String, String> attrMap =
                            Collections.singletonMap("java.home", systemJavaHome.toString());
                    jrtfs = FileSystems.newFileSystem(jrtURI, attrMap);
                } catch (ProviderNotFoundException ex) {
                    URL javaHomeURL = systemJavaHome.resolve("jrt-fs.jar").toUri().toURL();
                    ClassLoader currentLoader = Locations.class.getClassLoader();
                    URLClassLoader fsLoader =
                            new URLClassLoader(new URL[] {javaHomeURL}, currentLoader);

                    jrtfs = FileSystems.newFileSystem(jrtURI, Collections.emptyMap(), fsLoader);

                    closeables.add(fsLoader);
                }

                closeables.add(jrtfs);
            }

            modules = jrtfs.getPath("/modules");
        } catch (FileSystemNotFoundException | ProviderNotFoundException e) {
            modules = systemJavaHome.resolve("modules");
            if (!Files.exists(modules))
                throw new IOException("can't find system classes", e);
        }
    }

    moduleTable = new ModuleTable();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(modules, Files::isDirectory)) {
        for (Path entry : stream) {
            String moduleName = entry.getFileName().toString();
            String name = location.getName() + "[" + moduleName + "]";
            ModuleLocationHandler h = new ModuleLocationHandler(this,
                    name, moduleName, Collections.singletonList(entry), false);
            moduleTable.add(h);
        }
    }
}
 
源代码16 项目: openjdk-jdk9   文件: JRTIndex.java
/**
 * Create and initialize the index.
 */
private JRTIndex() throws IOException {
    jrtfs = FileSystems.getFileSystem(URI.create("jrt:/"));
    entries = new HashMap<>();
}
 
源代码17 项目: openjdk-jdk9   文件: Basic.java
@Test
public void testPackagesAndModules() throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    assertTrue(Files.isDirectory(fs.getPath("/packages")));
    assertTrue(Files.isDirectory(fs.getPath("/modules")));
}
 
源代码18 项目: openjdk-jdk9   文件: Basic.java
@Test(dataProvider = "packagesSubDirs")
public void testPackagesSubDirs(String pkg) throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    assertTrue(Files.isDirectory(fs.getPath("/packages/" + pkg)),
        pkg + " missing");
}
 
源代码19 项目: openjdk-jdk9   文件: Task.java
static List<Class<?>> getClasses(int count) throws Exception {
    List<Class<?>> classes = new ArrayList<>();
    FileSystem fs = null;

    try {
        fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    } catch (ProviderNotFoundException | FileSystemNotFoundException e) {
        throw new RuntimeException("FAIL - JRT Filesystem not found");
    }

    List<String> fileNames;
    Path modules = fs.getPath("/modules");

    Predicate<String> startsWithJavaBase          = path -> path.toString().startsWith("java.base/java");
    Predicate<String> startsWithJavaDesktop       = path -> path.toString().startsWith("java.desktop/java");
    Predicate<String> startsWithJavaDataTransfer  = path -> path.toString().startsWith("java.datatransfer/java");
    Predicate<String> startsWithJavaRMI           = path -> path.toString().startsWith("java.rmi/java");
    Predicate<String> startsWithJavaSmartCardIO   = path -> path.toString().startsWith("java.smartcardio/java");
    Predicate<String> startsWithJavaManagement    = path -> path.toString().startsWith("java.management/java");
    Predicate<String> startsWithJavaXML           = path -> path.toString().startsWith("java.xml/java");
    Predicate<String> startsWithJavaXMLBind       = path -> path.toString().startsWith("java.xml.bind/java");
    Predicate<String> startsWithJavaScripting     = path -> path.toString().startsWith("java.scripting/java");
    Predicate<String> startsWithJavaNaming        = path -> path.toString().startsWith("java.naming/java");
    Predicate<String> startsWithJavaSQL           = path -> path.toString().startsWith("java.sql/java");
    Predicate<String> startsWithJavaActivation    = path -> path.toString().startsWith("java.activation/java");
    Predicate<String> startsWithJavaCompiler      = path -> path.toString().startsWith("java.compiler/java");
    Predicate<String> startsWithJavaAnnotations   = path -> path.toString().startsWith("java.annotations/java");
    Predicate<String> startsWithJavaTransaction   = path -> path.toString().startsWith("java.transaction/java");
    Predicate<String> startsWithJavaLogging       = path -> path.toString().startsWith("java.logging/java");
    Predicate<String> startsWithJavaCorba         = path -> path.toString().startsWith("java.corba/java");
    Predicate<String> startsWithJavaPrefs         = path -> path.toString().startsWith("java.prefs/java");

    fileNames = Files.walk(modules)
            .map(Path::toString)
            .filter(path -> path.toString().contains("java"))
            .map(s -> s.substring(9))  // remove /modules/ from beginning
            .filter(startsWithJavaBase
                .or(startsWithJavaDesktop)
                .or(startsWithJavaDataTransfer)
                .or(startsWithJavaRMI)
                .or(startsWithJavaSmartCardIO)
                .or(startsWithJavaManagement)
                .or(startsWithJavaXML)
                .or(startsWithJavaXMLBind)
                .or(startsWithJavaScripting)
                .or(startsWithJavaNaming)
                .or(startsWithJavaSQL)
                .or(startsWithJavaActivation)
                .or(startsWithJavaCompiler)
                .or(startsWithJavaAnnotations)
                .or(startsWithJavaTransaction)
                .or(startsWithJavaLogging)
                .or(startsWithJavaCorba)
                .or(startsWithJavaPrefs))
            .map(s -> s.replace('/', '.'))
            .filter(path -> path.toString().endsWith(".class"))
            .map(s -> s.substring(0, s.length() - 6))  // drop .class
            .map(s -> s.substring(s.indexOf(".")))
            .filter(path -> path.toString().contains("java"))
            .map(s -> s.substring(s.indexOf("java")))
            .collect(Collectors.toList());

    for (String name : fileNames) {
        classes.add(Class.forName(name));
        if (count == classes.size()) {
            break;
        }
    }

    return classes;
}
 
源代码20 项目: Bytecoder   文件: ModularRuntimeImage.java
/**
 * Constructs a default instance.
 *
 * @throws IOException
 *             an I/O error occurs accessing the file system
 */
public ModularRuntimeImage() throws IOException {
    this(null, FileSystems.getFileSystem(URI.create("jrt:/")));
}