当前位置: 首页>>代码示例>>Java>>正文


Java FileSystems类代码示例

本文整理汇总了Java中java.nio.file.FileSystems的典型用法代码示例。如果您正苦于以下问题:Java FileSystems类的具体用法?Java FileSystems怎么用?Java FileSystems使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


FileSystems类属于java.nio.file包,在下文中一共展示了FileSystems类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getConfig

import java.nio.file.FileSystems; //导入依赖的package包/类
@Override
public Config getConfig() throws IOException {
  PathMatcher pathMatcher;

  try {
    pathMatcher = FileSystems.getDefault().getPathMatcher(inputFilePattern);
  } catch (IllegalArgumentException e) {
    throw new IllegalArgumentException(
        "Invalid input file pattern: " + inputFilePattern);
  }

  try (Stream<Path> pathStream = Files.walk(baseDirectory)) {
    return pathStream
        .filter(p -> Files.isRegularFile(p) && pathMatcher.matches(p))
        .map(p -> ConfigFactory.parseFile(p.toFile()))
        .reduce(ConfigFactory.empty(), Config::withFallback)
        .resolve(
            ConfigResolveOptions.defaults()
                .setAllowUnresolved(true)
                .setUseSystemEnvironment(false)
        );
  }
}
 
开发者ID:okvee,项目名称:tscfg-docgen,代码行数:24,代码来源:PathMatcherConfigProvider.java

示例2: create

import java.nio.file.FileSystems; //导入依赖的package包/类
public static Path create( URI uri )
{
  try
  {
    return Paths.get( uri );
  }
  catch( FileSystemNotFoundException nfe )
  {
    try
    {
      Map<String, String> env = new HashMap<>();
      env.put( "create", "true" ); // creates zip/jar file if not already exists
      FileSystem fs = FileSystems.newFileSystem( uri, env );
      return fs.provider().getPath( uri );
    }
    catch( IOException e )
    {
      throw new RuntimeException( e );
    }
  }
}
 
开发者ID:manifold-systems,项目名称:manifold,代码行数:22,代码来源:PathUtil.java

示例3: toPath

import java.nio.file.FileSystems; //导入依赖的package包/类
/**
 * 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 + "'");
    }
}
 
开发者ID:RBMHTechnology,项目名称:vind,代码行数:33,代码来源:FileSystemUtils.java

示例4: writeSnapshot

import java.nio.file.FileSystems; //导入依赖的package包/类
@Override
public void writeSnapshot(String snapshotDir) {
    // 采用软链接形式,提升速度和节省空间
    try {
        File messageDirFile = new File(messageDir);
        File snapshotDirFile = new File(snapshotDir);
        if (snapshotDirFile.exists()) {
            FileUtils.deleteDirectory(snapshotDirFile);
        }
        if (messageDirFile.exists()) {
            Path link = FileSystems.getDefault().getPath(snapshotDir);
            Path target = FileSystems.getDefault().getPath(messageDir).toRealPath();
            Files.createSymbolicLink(link, target);
        }
    } catch (IOException ex) {
        LOG.warn("write snapshot failed, exception:", ex);
    }
}
 
开发者ID:wenweihu86,项目名称:distmq,代码行数:19,代码来源:BrokerStateMachine.java

示例5: setup

import java.nio.file.FileSystems; //导入依赖的package包/类
@BeforeClass
public void setup() {
    theFileSystem = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path modulesPath = Paths.get(System.getProperty("java.home"),
            "lib", "modules");
    isExplodedBuild = Files.notExists(modulesPath);
    if (isExplodedBuild) {
        System.out.printf("%s doesn't exist.", modulesPath.toString());
        System.out.println();
        System.out.println("It is most probably an exploded build."
                + " Skip non-default FileSystem testing.");
        return;
    }

    Map<String, String> env = new HashMap<>();
    // set java.home property to be underlying java.home
    // so that jrt-fs.jar loading is exercised.
    env.put("java.home", System.getProperty("java.home"));
    try {
        fs = FileSystems.newFileSystem(URI.create("jrt:/"), env);
    } catch (IOException ioExp) {
        throw new RuntimeException(ioExp);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:Basic.java

示例6: Watchdog

import java.nio.file.FileSystems; //导入依赖的package包/类
/**
 * Initiates a Watchdog for specific resource. File must be located within
 * the resources location of a dev machine or within
 * {@code {catalina.home}/properties}
 * 
 */
public Watchdog(final DynamicLoadable loader, final boolean startImmediately) {
	if (loader == null) {
		throw new IllegalArgumentException("loader must be set");
	}
	resource = loader.getResourceFilename();
	if (resource == null) {
		throw new IllegalArgumentException("resource in loader must be set");
	}
	autostart = startImmediately;
	this.loader = loader;
	try {
		watchService = FileSystems.getDefault().newWatchService();
		final String path = loader.getResourceLocation();
		logger.info("Watchdog [" + path + "]");
		logger.info("INFO: Watchdog [" + path + resource + "]");
		Paths.get(path).register(watchService, ENTRY_MODIFY);
	} catch (final IOException e) {
		logger.warning(e.getMessage());
	}
}
 
开发者ID:ad-tech-group,项目名称:openssp,代码行数:27,代码来源:Watchdog.java

示例7: WatchDir

import java.nio.file.FileSystems; //导入依赖的package包/类
/**
 * Creates a WatchService and registers the given directory
 */
WatchDir(Path dir, boolean recursive) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.keys = new HashMap<WatchKey, Path>();
    this.recursive = recursive;

    if (recursive) {
        System.out.format("Scanning %s ...\n", dir);
        registerAll(dir);
        System.out.println("Done.");
    } else {
        register(dir);
    }

    // enable trace after initial registration
    this.trace = true;
}
 
开发者ID:robinhowlett,项目名称:handycapper,代码行数:20,代码来源:WatchDir.java

示例8: test

import java.nio.file.FileSystems; //导入依赖的package包/类
@Test
public void test() throws Exception {
    Path path = FileSystems.getDefault().getPath("", "index");
    Directory directory = FSDirectory.open(path);
    Analyzer analyzer = new StandardAnalyzer();
    IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer).setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
    Document document = new Document();
    document.add(new LegacyLongField("id", 5499, Field.Store.YES));
    document.add(new Field("title", "小米6", TYPE_STORED));
    document.add(new Field("sellPoint", "骁龙835,6G内存,双摄!", TYPE_STORED));
    document.
    indexWriter.addDocument(document);
    indexWriter.commit();
    indexWriter.close();
}
 
开发者ID:felayman,项目名称:elasticsearch-full,代码行数:17,代码来源:CreateIndexDemo.java

示例9: testNumberSuffixMatches

import java.nio.file.FileSystems; //导入依赖的package包/类
@Test
public void testNumberSuffixMatches() {
    final FileSystem fs = FileSystems.getDefault();
    final Path baseName = fs.getPath("/tmp", "logfile.log");
    final NumberSuffixStrategy m = new NumberSuffixStrategy(baseName);

    assertTrue("same file matches", m.pathMatches(fs.getPath("/tmp", "logfile.log")));
    assertTrue("number suffix matches", m.pathMatches(fs.getPath("/tmp", "logfile.log.1")));
    assertTrue("multi-digit suffix matches", m.pathMatches(fs.getPath("/tmp", "logfile.log.1345345")));
    assertFalse("separator must be '.'", m.pathMatches(fs.getPath("/tmp", "logfile.log-123")));
    assertFalse("more suffixes don't match", m.pathMatches(fs.getPath("/tmp", "logfile.log.1234.gz")));
    assertFalse("wrong base path doesn't match", m.pathMatches(fs.getPath("/var/log", "logfile.log.1234")));

    assertTrue("paths are normalized", m.pathMatches(fs.getPath("/tmp/bar/..", "logfile.log.1")));
    assertTrue("relative paths are resolved", m.pathMatches(fs.getPath("logfile.log.1")));

}
 
开发者ID:DevOpsStudio,项目名称:Re-Collector,代码行数:18,代码来源:FileNamingStrategyTest.java

示例10: loadExtensions

import java.nio.file.FileSystems; //导入依赖的package包/类
private Map<String, Accessible> loadExtensions() {
    Map<String, Accessible> accessibleMap = new HashMap<>();

    pluginManager = new DefaultPluginManager(
            FileSystems.getDefault().getPath(MainVerticle.pluginDir).toAbsolutePath());
    pluginManager.loadPlugins();
    pluginManager.startPlugins();
    List<Accessible> accessibleList = pluginManager.getExtensions(Accessible.class);
    for (Accessible accessible : accessibleList) {
        String pluginName = accessible.getClass().getDeclaringClass().getName();

        logger.info("{} is loaded ...", pluginName);

        accessibleMap.put(pluginName, accessible);
    }

    return accessibleMap;
}
 
开发者ID:DTeam-Top,项目名称:dfx,代码行数:19,代码来源:PluginManagerVerticle.java

示例11: generate

import java.nio.file.FileSystems; //导入依赖的package包/类
public static void generate() throws IOException {
  int stringsPerFile = (1 << 14);
  for (int fileNumber = 0; fileNumber < 2; fileNumber++) {
    Path path = FileSystems.getDefault().getPath("StringPool" + fileNumber + ".java");
    PrintStream out = new PrintStream(
        Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND));

    out.println(
        "// Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file");
    out.println(
        "// for details. All rights reserved. Use of this source code is governed by a");
    out.println("// BSD-style license that can be found in the LICENSE file.");
    out.println("package jumbostring;");
    out.println();
    out.println("class StringPool" + fileNumber + " {");

    int offset = fileNumber * stringsPerFile;
    for (int i = offset; i < offset + stringsPerFile; i++) {
      out.println("  public static final String s" + i + " = \"" + i + "\";");
    }
    out.println("}");
    out.close();
  }
}
 
开发者ID:inferjay,项目名称:r8,代码行数:25,代码来源:JumboString.java

示例12: getFileSystem

import java.nio.file.FileSystems; //导入依赖的package包/类
/**
 * Returns a new FileSystem to read REST resources, or null if they
 * are available from classpath.
 */
@SuppressForbidden(reason = "proper use of URL, hack around a JDK bug")
protected static FileSystem getFileSystem() throws IOException {
    // REST suite handling is currently complicated, with lots of filtering and so on
    // For now, to work embedded in a jar, return a ZipFileSystem over the jar contents.
    URL codeLocation = FileUtils.class.getProtectionDomain().getCodeSource().getLocation();
    boolean loadPackaged = RandomizedTest.systemPropertyAsBoolean(REST_LOAD_PACKAGED_TESTS, true);
    if (codeLocation.getFile().endsWith(".jar") && loadPackaged) {
        try {
            // hack around a bug in the zipfilesystem implementation before java 9,
            // its checkWritable was incorrect and it won't work without write permissions.
            // if we add the permission, it will open jars r/w, which is too scary! so copy to a safe r-w location.
            Path tmp = Files.createTempFile(null, ".jar");
            try (InputStream in = FileSystemUtils.openFileURLStream(codeLocation)) {
                Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING);
            }
            return FileSystems.newFileSystem(new URI("jar:" + tmp.toUri()), Collections.emptyMap());
        } catch (URISyntaxException e) {
            throw new IOException("couldn't open zipfilesystem: ", e);
        }
    } else {
        return null;
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:28,代码来源:ESClientYamlSuiteTestCase.java

示例13: validate

import java.nio.file.FileSystems; //导入依赖的package包/类
static void validate(Module module) throws IOException {
    ModuleDescriptor md = module.getDescriptor();

    // read m1/module-info.class
    FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"),
                                              Collections.emptyMap());
    Path path = fs.getPath("/", "modules", module.getName(), "module-info.class");
    ModuleDescriptor md1 = ModuleDescriptor.read(Files.newInputStream(path));


    // check the module descriptor of a system module and read from jimage
    checkPackages(md.packages(), "p1", "p2");
    checkPackages(md1.packages(), "p1", "p2");

    try (InputStream in = Files.newInputStream(path)) {
        checkModuleTargetAttribute(in, "p1");
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:19,代码来源:Main.java

示例14: testNewFileSystem

import java.nio.file.FileSystems; //导入依赖的package包/类
@Test
public void testNewFileSystem() throws IOException {
    for (String[] params : new String[][] {
        // $uri, $mountPoint
        { "tpath:/", "file:/" },
        { "tpath:///", "file:/" },
        { "tpath:/foo", "file:/" },
        { "tpath:/foo/", "file:/" },
        { "tpath:/foo/bar", "file:/foo/" },
        { "tpath:/foo/bar/", "file:/foo/" },
        { "tpath:/foo/bar.mok/", "mok:file:/foo/bar.mok!/" },
        { "tpath:/foo.mok/bar", "mok:file:/foo.mok!/" },
        { "tpath:/foo.mok/bar.mok", "mok:mok:file:/foo.mok!/bar.mok!/" },
    }) {
        final URI uri = URI.create(params[0]);
        final FsMountPoint mountPoint = FsMountPoint.create(
                URI.create(params[1]));
        final TFileSystem fs = (TFileSystem) FileSystems.newFileSystem(
                uri, getEnvironment(), TFileSystemTest.class.getClassLoader());
        fs.close();
        assertThat(fs.isOpen(), is(true));
        assertThat(fs.getMountPoint(), is(mountPoint));
    }
}
 
开发者ID:christian-schlichtherle,项目名称:truevfs,代码行数:25,代码来源:TFileSystemTest.java

示例15: watch

import java.nio.file.FileSystems; //导入依赖的package包/类
/**
 * Run the handler, wait for file change and interval.
 * This function exits if {@link InterruptedException} is occurred.
 * @param baseDirectory
 * @param interval
 * @param handler
 */
public void watch(File baseDirectory, Duration interval, Runnable handler) {
    while (true) {
        try {
            handler.run();
            try (val watchService = FileSystems.getDefault().newWatchService()) {
                register(watchService, baseDirectory);
                log.info("Waiting for change of file or directory in {}", baseDirectory.getAbsolutePath());
                waitForFileChange(watchService);
                log.info("File or directory has been changed, waiting {} sec...", interval.getSeconds());
                Thread.sleep(interval.toMillis());
            } catch (InterruptedException e) {
                log.info("Thread has been interrupted: {}", e.toString());
                return;
            }
        } catch (Exception e1) {
            log.warn("Error occurred while watching directory, retrying...", e1);
            try {
                Thread.sleep(interval.toMillis());
            } catch (InterruptedException e2) {
                log.info("Thread has been interrupted: {}", e2.toString());
                return;
            }
        }
    }
}
 
开发者ID:int128,项目名称:httpstub,代码行数:33,代码来源:DirectoryWatcher.java


注:本文中的java.nio.file.FileSystems类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。