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

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

源代码1 项目: quarkus   文件: ModelUtils.java
static Model readAppModel(Path appJar) throws IOException {
    try (FileSystem fs = FileSystems.newFileSystem(appJar, (ClassLoader) null)) {
        final Path metaInfMaven = fs.getPath("META-INF", "maven");
        if (Files.exists(metaInfMaven)) {
            try (DirectoryStream<Path> groupIds = Files.newDirectoryStream(metaInfMaven)) {
                for (Path groupIdPath : groupIds) {
                    if (!Files.isDirectory(groupIdPath)) {
                        continue;
                    }
                    try (DirectoryStream<Path> artifactIds = Files.newDirectoryStream(groupIdPath)) {
                        for (Path artifactIdPath : artifactIds) {
                            if (!Files.isDirectory(artifactIdPath)) {
                                continue;
                            }
                            final Path pomXml = artifactIdPath.resolve("pom.xml");
                            if (Files.exists(pomXml)) {
                                return readModel(pomXml);
                            }
                        }
                    }
                }
            }
        }
        throw new IOException("Failed to located META-INF/maven/<groupId>/<artifactId>/pom.xml in " + appJar);
    }
}
 
源代码2 项目: quarkus   文件: ZipUtils.java
/**
 * This call is not thread safe, a single of FileSystem can be created for the
 * profided uri until it is closed.
 * 
 * @param uri The uri to the zip file.
 * @param env Env map.
 * @return A new FileSystem.
 * @throws IOException in case of a failure
 */
public static FileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException {
    // If Multi threading required, logic should be added to wrap this fs
    // onto a fs that handles a reference counter and close the fs only when all thread are done
    // with it.
    try {
        return FileSystems.newFileSystem(uri, env);
    } catch (IOException | ZipError ioe) {
        // TODO: (at a later date) Get rid of the ZipError catching (and instead only catch IOException)
        //  since it's a JDK bug which threw the undeclared ZipError instead of an IOException.
        //  Java 9 fixes it https://bugs.openjdk.java.net/browse/JDK-8062754

        // include the URI for which the filesystem creation failed
        throw new IOException("Failed to create a new filesystem for " + uri, ioe);
    }
}
 
源代码3 项目: quarkus   文件: TestClassIndexer.java
public static Index indexTestClasses(Class<?> testClass) {
    final Indexer indexer = new Indexer();
    final Path testClassesLocation = getTestClassesLocation(testClass);
    try {
        if (Files.isDirectory(testClassesLocation)) {
            indexTestClassesDir(indexer, testClassesLocation);
        } else {
            try (FileSystem jarFs = FileSystems.newFileSystem(testClassesLocation, null)) {
                for (Path p : jarFs.getRootDirectories()) {
                    indexTestClassesDir(indexer, p);
                }
            }
        }
    } catch (IOException e) {
        throw new UncheckedIOException("Unable to index the test-classes/ directory.", e);
    }
    return indexer.complete();
}
 
源代码4 项目: openjdk-jdk9   文件: Main.java
private static void checkModule(String mn, String... packages) throws IOException {
    // verify ModuleDescriptor from the runtime module
    ModuleDescriptor md = ModuleLayer.boot().findModule(mn).get()
                               .getDescriptor();
    checkModuleDescriptor(md, packages);

    // verify ModuleDescriptor from module-info.class read from ModuleReader
    try (InputStream in = ModuleFinder.ofSystem().find(mn).get()
        .open().open("module-info.class").get()) {
        checkModuleDescriptor(ModuleDescriptor.read(in), packages);
    }

    // verify ModuleDescriptor from module-info.class read from jimage
    FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"),
        Collections.emptyMap());
    Path path = fs.getPath("/", "modules", mn, "module-info.class");
    checkModuleDescriptor(ModuleDescriptor.read(Files.newInputStream(path)), packages);
}
 
源代码5 项目: openjdk-jdk9   文件: JdepsConfiguration.java
SystemModuleFinder(String javaHome) throws IOException {
    if (javaHome == null) {
        // --system none
        this.fileSystem = null;
        this.root = null;
        this.systemModules = Collections.emptyMap();
    } else {
        if (Files.isRegularFile(Paths.get(javaHome, "lib", "modules")))
            throw new IllegalArgumentException("Invalid java.home: " + javaHome);

        // alternate java.home
        Map<String, String> env = new HashMap<>();
        env.put("java.home", javaHome);
        // a remote run-time image
        this.fileSystem = FileSystems.newFileSystem(URI.create("jrt:/"), env);
        this.root = fileSystem.getPath("/modules");
        this.systemModules = walk(root);
    }
}
 
源代码6 项目: jdk8u-jdk   文件: ZipCat.java
/**
 * The main method for the ZipCat program. Run the program with an empty
 * argument list to see possible arguments.
 *
 * @param args the argument list for ZipCat
 */
public static void main(String[] args) {
    if (args.length != 2) {
        System.out.println("Usage: ZipCat zipfile fileToPrint");
    }
    /*
     * Creates AutoCloseable FileSystem and BufferedReader.
     * They will be closed automatically after the try block.
     * If reader initialization fails, then zipFileSystem will be closed
     * automatically.
     */
    try (FileSystem zipFileSystem
            = FileSystems.newFileSystem(Paths.get(args[0]),null);
            InputStream input
            = Files.newInputStream(zipFileSystem.getPath(args[1]))) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = input.read(buffer)) != -1) {
                    System.out.write(buffer, 0, len);
                }

    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}
 
源代码7 项目: j2cl   文件: FrontendUtils.java
public static FileSystem initZipOutput(String output, Problems problems) {
  Path outputPath = Paths.get(output);
  if (Files.isDirectory(outputPath)) {
    problems.fatal(FatalError.OUTPUT_LOCATION, outputPath);
  }

  // Ensures that we will not fail if the zip already exists.
  outputPath.toFile().delete();

  try {
    return FileSystems.newFileSystem(
        URI.create("jar:" + outputPath.toAbsolutePath().toUri()),
        ImmutableMap.of("create", "true"));
  } catch (IOException e) {
    problems.fatal(FatalError.CANNOT_CREATE_ZIP, outputPath, e.getMessage());
    return null;
  }
}
 
源代码8 项目: 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 + "'");
    }
}
 
源代码9 项目: raptor   文件: SchemaLoader.java
public Schema load() throws IOException {
  if (sources.isEmpty()) {
    throw new IllegalStateException("No sources added.");
  }

  try (Closer closer = Closer.create()) {
    // Map the physical path to the file system root. For regular directories the key and the
    // value are equal. For ZIP files the key is the path to the .zip, and the value is the root
    // of the file system within it.
    Map<Path, Path> directories = new LinkedHashMap<>();
    for (Path source : sources) {
      if (Files.isRegularFile(source)) {
        FileSystem sourceFs = FileSystems.newFileSystem(source, getClass().getClassLoader());
        closer.register(sourceFs);
        directories.put(source, getOnlyElement(sourceFs.getRootDirectories()));
      } else {
        directories.put(source, source);
      }
    }
    return loadFromDirectories(directories);
  }
}
 
源代码10 项目: Concurnas   文件: ConcSemanticsTests.java
@Test
public void mainifestMissingEntryPointJar() throws IOException {
	ConccTestMockFileLoader mockFL = new ConccTestMockFileLoader();
	
	Path jarPath = mockFL.fs.getPath("thing.jar");
	URI jarUri = URI.create("jar:" + jarPath.toUri());
	
	Map<String, String> env = new HashMap<String, String>();
	env.put("create", "true");
	try (FileSystem zipfs = FileSystems.newFileSystem(jarUri, env)) {
		Files.createDirectories(zipfs.getPath("/META-INF/"));
		Path manifest = zipfs.getPath("/META-INF/MANIFEST.MF");
		Files.write(manifest, ListMaker.make(""), StandardCharsets.UTF_8);
	}
	
	Conc concc = new Conc("thing.jar", mockFL);// ok
	
	TestCase.assertEquals("Manifest file META-INF/MANIFEST.MF is missing 'Main-Class' entry", concc.validateConcInstance(concc.getConcInstance()).validationErrs);
}
 
源代码11 项目: quarkus   文件: ZipResourceLoader.java
@Override
public <T> T loadResource(String name, ResourceInputStreamConsumer<T> consumer) throws IOException {
    try (FileSystem fs = FileSystems.newFileSystem(zip, (ClassLoader) null)) {
        final Path p = fs.getPath("/", name);
        if (!Files.exists(p)) {
            throw new IOException("Failed to locate " + name + " in " + zip);
        }
        try (InputStream is = Files.newInputStream(p)) {
            return consumer.consume(is);
        }
    }
}
 
源代码12 项目: openjdk-jdk9   文件: ModulesInCustomFileSystem.java
/**
 * Opens a JAR file as a file system
 */
private void testJarFileSystem(Path jar) throws Exception {
    ClassLoader scl = ClassLoader.getSystemClassLoader();
    try (FileSystem fs = FileSystems.newFileSystem(jar, scl)) {
        // ModuleFinder to find modules in top-level directory
        Path top = fs.getPath("/");
        ModuleFinder finder = ModuleFinder.of(top);

        // list the modules
        listAllModules(finder);

        // load modules into child layer, invoking m1/p.Main
        loadAndRunModule(finder);
    }
}
 
private FileSystem getFileSystem(Path p) throws IOException {
    FileSystem fs = fileSystems.get(p);
    if (fs == null) {
        fs = FileSystems.newFileSystem(p, null);
        fileSystems.put(p, fs);
    }
    return fs;
}
 
源代码14 项目: openjdk-jdk9   文件: Main.java
private static boolean hasModuleTarget(String modName) throws IOException {
    FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"),
                                              Collections.emptyMap());
    Path path = fs.getPath("/", "modules", modName, "module-info.class");
    try (InputStream in = Files.newInputStream(path)) {
        return hasModuleTarget(in);
    }
}
 
源代码15 项目: arcusplatform   文件: ClassPathJarResource.java
@Override
public boolean isReadable() {
   boolean rtn = false;
   try (FileSystem fileSystem = FileSystems.newFileSystem(this.jarRoot, Collections.<String, Object> emptyMap())) {
      Path fsPath = fileSystem.getPath(this.jarPath);
      rtn = fsPath != null && Files.isReadable(fsPath);
   }
   catch (IOException e) {
      logger.warn("Failed to close jar filesystem root [{}] during isReadable check of [{}]", this.jarRoot, this.path, e);
   }

   return rtn;
}
 
源代码16 项目: gate-core   文件: Plugin.java
public void walkResources(FileVisitor<? super Path> visitor) throws URISyntaxException, IOException {
  try (FileSystem zipFs =
               FileSystems.newFileSystem(artifactURL.toURI(), new HashMap<>())) {
    Path resourcesPath = zipFs.getPath("/resources");
    if(Files.isDirectory(resourcesPath)) {
      Files.walkFileTree(resourcesPath, visitor);
    }
  }
}
 
源代码17 项目: petscii-bbs   文件: PetsciiArtGallery.java
public List<Path> getDirContent(String path) throws URISyntaxException, IOException {
    List<Path> result = new ArrayList<>();
    URL jar = getClass().getProtectionDomain().getCodeSource().getLocation();
    Path jarFile = Paths.get(jar.toURI());
    try (FileSystem fs = FileSystems.newFileSystem(jarFile, NULL_CLASSLOADER);
        DirectoryStream<Path> directoryStream = Files.newDirectoryStream(fs.getPath(path))) {
        for (Path p : directoryStream) {
            result.add(p);
        }

        result.sort((o1, o2) -> o1 == null || o2 == null ? 0 :
                o1.getFileName().toString().compareTo(o2.getFileName().toString()));
        return result;
    }
}
 
源代码18 项目: gate-core   文件: Plugin.java
@Override
public void copyResources(File dir) throws URISyntaxException, IOException {

  if(!hasResources())
    throw new UnsupportedOperationException(
        "this plugin doesn't have any resources you can copy as you would know had you called hasResources first :P");
  
  Path target = Paths.get(dir.toURI());
  try (FileSystem zipFs =
      FileSystems.newFileSystem(getArtifactURL().toURI(), new HashMap<>());) {

    Path pathInZip = zipFs.getPath("/resources");

    Files.walkFileTree(pathInZip, new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path filePath,
          BasicFileAttributes attrs) throws IOException {
        // Make sure that we conserve the hierachy of files and folders
        // inside the zip
        Path relativePathInZip = pathInZip.relativize(filePath);
        Path targetPath = target.resolve(relativePathInZip.toString());
        Files.createDirectories(targetPath.getParent());

        // And extract the file
        Files.copy(filePath, targetPath,
            StandardCopyOption.REPLACE_EXISTING);

        return FileVisitResult.CONTINUE;
      }
    });
  } catch(Exception e) {
    // TODO Auto-generated catch block
    throw new IOException(e);
  }
}
 
源代码19 项目: openjdk-jdk8u   文件: JavacPathFileManager.java
private FileSystem getFileSystem(Path p) throws IOException {
    FileSystem fs = fileSystems.get(p);
    if (fs == null) {
        fs = FileSystems.newFileSystem(p, null);
        fileSystems.put(p, fs);
    }
    return fs;
}
 
源代码20 项目: Bytecoder   文件: ModularRuntimeImage.java
/**
 * Constructs an instance using the JRT file system implementation from a specific Java Home.
 *
 * @param javaHome
 *            Path to a Java 9 or greater home.
 *
 * @throws IOException
 *             an I/O error occurs accessing the file system
 */
public ModularRuntimeImage(final String javaHome) throws IOException {
    final Map<String, ?> emptyMap = Collections.emptyMap();
    final Path jrePath = Paths.get(javaHome);
    final Path jrtFsPath = jrePath.resolve("lib").resolve("jrt-fs.jar");
    this.classLoader = new URLClassLoader(new URL[] {jrtFsPath.toUri().toURL() });
    this.fileSystem = FileSystems.newFileSystem(URI.create("jrt:/"), emptyMap, classLoader);
}