Java 类java.nio.file.FileSystems 实例源码

项目:tscfg-docgen    文件:PathMatcherConfigProvider.java   
@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)
        );
  }
}
项目:distmq    文件:BrokerStateMachine.java   
@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);
    }
}
项目:openjdk-jdk10    文件:Basic.java   
@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);
    }
}
项目:openssp    文件:Watchdog.java   
/**
 * 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());
    }
}
项目:handycapper    文件:WatchDir.java   
/**
 * 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;
}
项目:elasticsearch-full    文件:CreateIndexDemo.java   
@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();
}
项目:Re-Collector    文件:FileNamingStrategyTest.java   
@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")));

}
项目:dfx    文件:PluginManagerVerticle.java   
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;
}
项目:r8    文件:JumboString.java   
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();
  }
}
项目:elasticsearch_my    文件:ESClientYamlSuiteTestCase.java   
/**
 * 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;
    }
}
项目:openjdk-jdk10    文件:Main.java   
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");
    }
}
项目:truevfs    文件:TFileSystemTest.java   
@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));
    }
}
项目:httpstub    文件:DirectoryWatcher.java   
/**
 * 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;
            }
        }
    }
}
项目:neoscada    文件:BaseWatcher.java   
public BaseWatcher ( final StorageManager storageManager, final File base ) throws IOException
{
    this.storageManager = storageManager;
    this.base = base.toPath ();
    this.watcher = FileSystems.getDefault ().newWatchService ();

    this.baseKey = base.toPath ().register ( this.watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE );

    logger.debug ( "Checking for initial storages" );

    for ( final File child : this.base.toFile ().listFiles () )
    {
        logger.debug ( "Found initial storage dir - {}", child );
        checkAddStorage ( child.toPath () );
    }

    startWatcher ();
}
项目:ios-device-control    文件:IosAppInfo.java   
/** Returns the application info read from either an app folder or ipa archive */
public static IosAppInfo readFromPath(Path ipaOrAppPath) throws IOException {
  NSObject plistDict;
  if (Files.isDirectory(ipaOrAppPath)) {
    plistDict = PlistParser.fromPath(ipaOrAppPath.resolve("Info.plist"));
  } else {
    try (FileSystem ipaFs = FileSystems.newFileSystem(ipaOrAppPath, null)) {
      Path appPath =
          MoreFiles.listFiles(ipaFs.getPath("Payload"))
              .stream()
              // Can't use Files.isDirectory, because no entry is a "directory" in a zip.
              .filter(e -> e.toString().endsWith(".app/"))
              .collect(MoreCollectors.onlyElement());
      plistDict = PlistParser.fromPath(appPath.resolve("Info.plist"));
    }
  }
  return readFromPlistDictionary((NSDictionary) plistDict);
}
项目:openjdk-jdk10    文件: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:/"), Map.of());
    Path path = fs.getPath("/", "modules", mn, "module-info.class");
    checkModuleDescriptor(ModuleDescriptor.read(Files.newInputStream(path)), packages);
}
项目:OperatieBRP    文件:TimestampMojo.java   
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (artifact.endsWith("jar") || artifact.endsWith("war")) {
        getLog().debug("Setting fixed timestamp for " + artifact);
        try {
            final Path tmpFolderPath = createTmpFolderPath();
            if (tmpFolderPath.toFile().exists()) {
                deleteTmpFolder(tmpFolderPath);
            }
            final Path tmpFolder = Files.createDirectory(tmpFolderPath);
            backupArtifact();
            Set<String> keys = pakArchiefBestandUit(tmpFolder);
            pakArchiefBestandOpnieuwIn(tmpFolder, keys);
            Files.deleteIfExists(FileSystems.getDefault().getPath(artifact + ".bak"));
            deleteTmpFolder(tmpFolder);
        } catch (IOException e) {
            throw new MojoExecutionException("Cannot create temp folder", e);
        }
    } else {
        getLog().debug("Artifact is not a jar or war file");
    }
}
项目: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 + "'");
    }
}
项目:manifold    文件:PathUtil.java   
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 );
    }
  }
}
项目:tdd-pingpong    文件:SubmissionPackagingService.java   
private void addTemplateFiles(ArchiveOutputStream archive) throws IOException {
  // TODO: maybe get the template path from config?
  Path templateDirectory = FileSystems.getDefault().getPath("tmc-assets", "submission-template");
  List<Path> templateEntries = getDirectoryEntries(templateDirectory);

  for (Path entry : templateEntries) {
    // Paths must be relativized against the template directory root
    // before including them into the Tar archive.
    // I.e. a file at ./tmc-assets/submission-template/directory/file.txt will be added to
    // the archive as ./directory/file.txt.
    String tarEntryName = templateDirectory.relativize(entry).toString();

    // TODO: special case for build.xml for renaming the project.
    addFile(archive, tarEntryName, entry);
  }
}
项目:xtf    文件:SshUtil.java   
public String getPrivateKeyPath() {

        Path p;

        String keyPath = TestConfiguration.masterSshKeyPath();

        if (keyPath != null) {
            p = FileSystems.getDefault().getPath(keyPath);

            if (p.toFile().exists()) {
                return p.toString();
            }

            p = IOUtils.findProjectRoot().resolve(keyPath);
            if (p.toFile().exists()) {
                return p.toString();
            }
        }

        p = FileSystems.getDefault().getPath("/ssh", "ssh-key");
        if (p.toFile().exists()) {
            return p.toString();
        }
        throw new SshPrivateKeyNotFoundException("Cannot load SSH private key.");
    }
项目:openjdk-jdk10    文件:ModuleSourceProviderTest.java   
@Before
public void setUp() {
    classLoader = new FakeClassLoader();
    fileSupport = new FileSupport() {

        @Override
        public boolean isDirectory(Path path) {
            return true;
        }

        @Override
        public Path getSubDirectory(FileSystem fileSystem, Path root, Path path) throws IOException {
            if (getSubDirectory == null) {
                throw new IOException("Nope");
            }
            return getSubDirectory.apply(root, path);
        }
    };
    target = new ModuleSourceProvider(FileSystems.getDefault(), classLoader, fileSupport);
}
项目:ditb    文件:TestUpdateConfiguration.java   
@Test
public void testMasterOnlineConfigChange() throws IOException {
  LOG.debug("Starting the test");
  Path cnfPath = FileSystems.getDefault().getPath("target/test-classes/hbase-site.xml");
  Path cnf2Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site2.xml");
  Path cnf3Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site3.xml");
  // make a backup of hbase-site.xml
  Files.copy(cnfPath, cnf3Path, StandardCopyOption.REPLACE_EXISTING);
  // update hbase-site.xml by overwriting it
  Files.copy(cnf2Path, cnfPath, StandardCopyOption.REPLACE_EXISTING);

  Admin admin = TEST_UTIL.getHBaseAdmin();
  ServerName server = TEST_UTIL.getHBaseCluster().getMaster().getServerName();
  admin.updateConfiguration(server);
  Configuration conf = TEST_UTIL.getMiniHBaseCluster().getMaster().getConfiguration();
  int custom = conf.getInt("hbase.custom.config", 0);
  assertEquals(custom, 1000);
  // restore hbase-site.xml
  Files.copy(cnf3Path, cnfPath, StandardCopyOption.REPLACE_EXISTING);
}
项目:Java-9-Programming-Blueprints    文件:FileFinder.java   
public void find() {
    matchers = patterns.stream()
            .map(s -> !s.startsWith("**") ? "**/" + s : s)
            .map(p -> FileSystems.getDefault().getPathMatcher("glob:" + p))
            .collect(Collectors.toList());
    sourcePaths.stream()
            .map(p -> new FindFileTask(p, matchers, factory))
            .forEach(fft -> es.execute(fft));
    try {
        es.shutdown();
        es.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }

    postProcessFiles();
    factory.close();
}
项目:openjdk-jdk10    文件:Basic.java   
@Test
public void testNewFileSystemWithJavaHome() throws Exception {
    if (isExplodedBuild) {
        System.out.println("Skip testNewFileSystemWithJavaHome"
                + " since this is an exploded build");
        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 (FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"), env)) {
        checkFileSystem(fs);
        // jrt-fs.jar classes are loaded by another (non-boot) loader in this case
        assertNotNull(fs.provider().getClass().getClassLoader());
    }
}
项目:hype    文件:Hypelet.java   
private static FileSystemProvider loadFileSystemProvider(URI uri) throws IOException {
  if (Objects.equals(uri.getScheme(), "file")) {
    return FileSystems.getFileSystem(URI.create("file:///")).provider();
  } else {
    return FileSystems.newFileSystem(uri, emptyMap(), Hypelet.class.getClassLoader()).provider();
  }
}
项目:openjdk-jdk10    文件:ExternalEditor.java   
/**
 * Creates a WatchService and registers the given directory
 */
private void setupWatch(String initialText) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.dir = Files.createTempDirectory("extedit");
    this.tmpfile = Files.createTempFile(dir, null, ".java");
    Files.write(tmpfile, initialText.getBytes(Charset.forName("UTF-8")));
    dir.register(watcher,
            ENTRY_CREATE,
            ENTRY_DELETE,
            ENTRY_MODIFY);
    watchedThread = new Thread(() -> {
        for (;;) {
            WatchKey key;
            try {
                key = watcher.take();
            } catch (ClosedWatchServiceException ex) {
                // The watch service has been closed, we are done
                break;
            } catch (InterruptedException ex) {
                // tolerate an interrupt
                continue;
            }

            if (!key.pollEvents().isEmpty()) {
                saveFile();
            }

            boolean valid = key.reset();
            if (!valid) {
                // The watch service has been closed, we are done
                break;
            }
        }
    });
    watchedThread.start();
}
项目:distmq    文件:BrokerStateMachine.java   
@Override
public void readSnapshot(String snapshotDir) {
    try {
        isAvailable.compareAndSet(true, false);
        Path link = FileSystems.getDefault().getPath(snapshotDir);
        if (!Files.isSymbolicLink(link)) {
            // 非符号链接,表示从leader节点同步拷贝的
            if (logManager != null) {
                logManager.close();
            }
            File snapshotDirFile = new File(snapshotDir);
            if (snapshotDirFile.exists() && snapshotDirFile.listFiles().length > 0) {
                File messageDirFile = new File(messageDir);
                if (messageDirFile.exists()) {
                    FileUtils.deleteDirectory(messageDirFile);
                }
                FileUtils.copyDirectory(snapshotDirFile, messageDirFile);
            }
        }
        logManager = new LogManager(messageDir, this);
    } catch (IOException ex) {
        LOG.error("readSnapshot exception:", ex);
        throw new RuntimeException(ex);
    } finally {
        isAvailable.compareAndSet(false,  true);
    }
}
项目:distmq    文件:Segment.java   
public Segment(String dirName, String fileName) {
    this.dirName = dirName;
    this.fileName = fileName;
    String[] splitArray = fileName.split("-");
    if (splitArray.length != 2) {
        LOG.error("segment filename is not valid, segmentDir={}, file={}",
                dirName, fileName);
        throw new RuntimeException("invalid segmentDir=" + dirName);
    }
    try {
        if (splitArray[0].equals("open")) {
            this.setCanWrite(true);
            this.setStartOffset(Long.valueOf(splitArray[1]));
            this.setEndOffset(0);
        } else {
            try {
                this.setCanWrite(false);
                this.setStartOffset(Long.parseLong(splitArray[0]));
                this.setEndOffset(Long.parseLong(splitArray[1]));
            } catch (NumberFormatException ex) {
                LOG.error("invalid segment file name:{}", fileName);
                throw new RuntimeException("invalid segmentDir=" + dirName);
            }
        }
        File file = new File(dirName + File.separator + fileName);
        if (!file.exists()) {
            Path path = FileSystems.getDefault().getPath(dirName, fileName);
            Files.createFile(path);
        }
        this.setRandomAccessFile(RaftFileUtils.openFile(dirName, fileName, "rw"));
        this.setChannel(this.randomAccessFile.getChannel());
        this.setFileSize(this.randomAccessFile.length());
    } catch (IOException ioException) {
        LOG.warn("open segment file error, file={}, msg={}",
                fileName, ioException.getMessage());
        throw new RuntimeException("open segment file error");
    }
}
项目:axway-b2b-plugins    文件:GlobValidator.java   
@Override
public boolean isValid(String input, String pattern) {
    PathMatcher matcher = FileSystems.getDefault().getPathMatcher(GLOB_KEYWORD + pattern);
    Path keyPath = Paths.get(input, new String[0]);

    return matcher.matches(keyPath);
}
项目:openjdk-jdk10    文件:JmodTask.java   
@Override
public PathMatcher convert(String pattern) {
    try {
        return Utils.getPathMatcher(FileSystems.getDefault(), pattern);
    } catch (PatternSyntaxException e) {
        throw new CommandException("err.bad.pattern", pattern);
    }
}
项目:openjdk-jdk10    文件:CustomLauncherTest.java   
private static String[] getLauncher() throws IOException {
    String platform = getPlatform();
    if (platform == null) {
        return null;
    }

    String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
                      File.separator + "launcher";

    final FileSystem FS = FileSystems.getDefault();
    Path launcherPath = FS.getPath(launcher);

    final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
                                Files.isReadable(launcherPath);
    if (!hasLauncher) {
        System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
        return null;
    }

    // It is impossible to store an executable file in the source control
    // We need to copy the launcher to the working directory
    // and set the executable flag
    Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
    Files.copy(launcherPath, localLauncherPath,
               StandardCopyOption.REPLACE_EXISTING);
    if (!Files.isExecutable(localLauncherPath)) {
        Set<PosixFilePermission> perms = new HashSet<>(
            Files.getPosixFilePermissions(
                localLauncherPath,
                LinkOption.NOFOLLOW_LINKS
            )
        );
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(localLauncherPath, perms);
    }
    return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
项目:incubator-netbeans    文件:FileUtils.java   
public static File getNormalizedPathFile(File file) {
    if (file != null && !file.getPath().isEmpty()) {
        try {
            Path path = FileSystems.getDefault().getPath(file.getPath());

            if (path != null) {
                return path.normalize().toFile();
            }
        } catch(InvalidPathException ex) {
            LogManager.log("Trying to normalize invalid path", ex);
        }                            
    }

    return file;
}
项目:openjdk-jdk10    文件:CodeStoreAndPathTest.java   
private static Path getCodeCachePath(final boolean optimistic) {
    final String codeCache = System.getProperty("nashorn.persistent.code.cache");
    final Path codeCachePath = FileSystems.getDefault().getPath(codeCache).toAbsolutePath();
    final String[] files = codeCachePath.toFile().list();
    for (final String file : files) {
        if (file.endsWith("_opt") == optimistic) {
            return codeCachePath.resolve(file);
        }
    }
    throw new AssertionError("Code cache path not found: " + codeCachePath.toString());
}
项目:springboot-shiro-cas-mybatis    文件:JsonServiceRegistryConfigWatcher.java   
/**
 * Instantiates a new Json service registry config watcher.
 *
 * @param serviceRegistryDao the registry to callback
 */
public JsonServiceRegistryConfigWatcher(final JsonServiceRegistryDao serviceRegistryDao) {
    try {
        this.serviceRegistryDao = serviceRegistryDao;
        this.watcher = FileSystems.getDefault().newWatchService();
        final WatchEvent.Kind[] kinds = (WatchEvent.Kind[])
                Arrays.asList(ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY).toArray();
        this.serviceRegistryDao.getServiceRegistryDirectory().register(this.watcher, kinds);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}
项目:powsybl-core    文件:Main.java   
public static void main(String[] args) throws IOException {
    int status = new CommandLineTools().run(args, new ToolInitializationContext() {
        @Override
        public PrintStream getOutputStream() {
            return System.out;
        }

        @Override
        public PrintStream getErrorStream() {
            return System.err;
        }

        @Override
        public FileSystem getFileSystem() {
            return FileSystems.getDefault();
        }

        @Override
        public Options getAdditionalOptions() {
            return new Options();
        }

        @Override
        public ComputationManager createComputationManager(CommandLine commandLine) {
            try {
                return new LocalComputationManager();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    });
    if (status != CommandLineTools.COMMAND_OK_STATUS) {
        System.exit(status);
    }
}
项目:openjdk-jdk10    文件:FSInfo.java   
public List<Path> getJarClassPath(Path file) throws IOException {
    Path parent = file.getParent();
    try (JarFile jarFile = new JarFile(file.toFile())) {
        Manifest man = jarFile.getManifest();
        if (man == null)
            return Collections.emptyList();

        Attributes attr = man.getMainAttributes();
        if (attr == null)
            return Collections.emptyList();

        String path = attr.getValue(Attributes.Name.CLASS_PATH);
        if (path == null)
            return Collections.emptyList();

        List<Path> list = new ArrayList<>();

        for (StringTokenizer st = new StringTokenizer(path);
             st.hasMoreTokens(); ) {
            String elt = st.nextToken();
            Path f = FileSystems.getDefault().getPath(elt);
            if (!f.isAbsolute() && parent != null)
                f = parent.resolve(f).toAbsolutePath();
            list.add(f);
        }

        return list;
    }
}
项目:vrap    文件:WebJarHandler.java   
private FileSystem initJarFileSystem(final URI uri) {
    try {
        return FileSystems.newFileSystem(uri, Collections.emptyMap());
    } catch (IOException e) {
        throw uncheck(e);
    }
}
项目:cas-5.1.0    文件:ConfigurationDirectoryPathWatchService.java   
public ConfigurationDirectoryPathWatchService(final Path directory, final ApplicationEventPublisher eventPublisher) {
    this.eventPublisher = eventPublisher;

    try {
        this.directory = directory;
        this.watcher = FileSystems.getDefault().newWatchService();
        this.directory.register(this.watcher,
                ENTRY_CREATE,
                ENTRY_DELETE,
                ENTRY_MODIFY);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
项目:cas-5.1.0    文件:ServiceRegistryConfigWatcher.java   
/**
 * Instantiates a new Json service registry config watcher.
 *
 * @param serviceRegistryDao the registry to callback
 */
ServiceRegistryConfigWatcher(final ResourceBasedServiceRegistryDao serviceRegistryDao,
                             final ApplicationEventPublisher eventPublisher) {
    try {
        this.serviceRegistryDao = serviceRegistryDao;
        this.watcher = FileSystems.getDefault().newWatchService();
        final WatchEvent.Kind[] kinds = new WatchEvent.Kind[]{ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY};
        LOGGER.debug("Created service registry watcher for events of type [{}]", (Object[]) kinds);
        this.serviceRegistryDao.getWatchableResource().register(this.watcher, kinds);

        this.applicationEventPublisher = eventPublisher;
    } catch (final IOException e) {
        throw Throwables.propagate(e);
    }
}