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

项目:MSFTBX    文件:FileListing.java   
/**
 *
 * @return
 */
public List<Path> findFiles() {
    LinkOption[] options;
    if (followLinks) {
        options = new LinkOption[0];
    } else {
        options = new LinkOption[]{LinkOption.NOFOLLOW_LINKS};
    }
    if (includeFiles && !Files.isDirectory(path, options)) {
        // if a single file was given, just check it against the pattern
        if (matches(path)) {
            return Collections.singletonList(path);
        }
    } else {
        // a directory was given, let's search it
        ArrayList<Path> result = new ArrayList<>();
        if (includeDirectories && matches(path)) {
            // check the top-level directory
            result.add(path);
        }
        findFiles(path, result, options, 0);
        return result;
    }
    return Collections.emptyList();
}
项目:ParquetUtils    文件:HDFSUtils.java   
public static Configuration getConfiguration(String pathConf) {

        // System.setProperty("hadoop.home.dir", "/");
        Configuration conf = new Configuration();

        /*
         * The following two instructions resolve the file system overwriting
         * issues (cfr.
         * http://stackoverflow.com/questions/17265002/hadoop-no-filesystem-for-
         * scheme-file)
         */
        conf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
        conf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName());

        java.nio.file.Path path = Paths.get(pathConf);
        if( Files.exists(path, LinkOption.NOFOLLOW_LINKS) ) {
            conf.addResource(pathConf);
        } else {
            System.err.println("The path of namenode configuration file is wrong");
            System.exit(1);
        }

        return conf;
    }
项目:rapidminer    文件:JVMOptionBuilder.java   
private static void addSystemSpecificSettings(StringBuilder builder) {
    if(SystemInfoUtilities.getOperatingSystem() == OperatingSystem.OSX) {
        String dockIconPath = null;
        String platformIndependent = PlatformUtilities.getRapidMinerHome() + "/RapidMiner Studio.app/Contents/Resources/rapidminer_frame_icon.icns";
        if(Files.exists(Paths.get(platformIndependent, new String[0]), new LinkOption[0])) {
            dockIconPath = platformIndependent;
        } else {
            dockIconPath = PlatformUtilities.getRapidMinerHome() + "/../rapidminer_frame_icon.icns";
        }

        builder.append(" -Xdock:icon=");
        builder.append(escapeBlanks(dockIconPath));
        builder.append(" -Xdock:name=");
        builder.append(escapeBlanks("RapidMiner"));
        builder.append(" -Dcom.apple.mrj.application.apple.menu.about.name=");
        builder.append(escapeBlanks("RapidMiner"));
        builder.append(" -Dapple.laf.useScreenMenuBar=true");
        builder.append(" -Dcom.apple.mrj.application.growbox.intrudes=true");
        builder.append(" -Dapple.awt.antialiasing=true");
        builder.append(" -Dcom.apple.mrj.application.live-resize=true");
        builder.append(" -Dsun.java2d.opengl=true");
    } else if(SystemInfoUtilities.getOperatingSystem() == OperatingSystem.WINDOWS) {
        builder.append(" -Djava.net.preferIPv4Stack=true");
    }

}
项目:alfresco-repository    文件:FileUtils.java   
public static String getFileName(final Path path)
{
    String result = null;

    if (path != null)
    {
        try
        {
            result = path.toRealPath(LinkOption.NOFOLLOW_LINKS).toString();
        }
        catch (final IOException ioe)
        {
            result = path.toString();
        }
    }

    return result;
}
项目:Equella    文件:FileUtils.java   
public static long countFiles(Path file)
{
    if( !Files.exists(file, LinkOption.NOFOLLOW_LINKS) )
    {
        return 0;
    }
    try
    {
        CountingVisitor visitor = new CountingVisitor();
        Files.walkFileTree(file, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, visitor);
        return visitor.getCount();
    }
    catch( Exception e )
    {
        throw new RuntimeException("Error counting files for " + file.toString(), e);
    }
}
项目:Equella    文件:FileUtils.java   
public static long fileSize(Path file) throws FileNotFoundException
{
    if( Files.exists(file, LinkOption.NOFOLLOW_LINKS) )
    {
        try
        {
            return Files.size(file);
        }
        catch( IOException io )
        {
            LOGGER.error("Error getting file size for " + file.toString(), io);
            throw new RuntimeException(io);
        }
    }
    throw new FileNotFoundException(file.toString());
}
项目:Java_Swing_Programming    文件:Ornek6.java   
private void tbl_listeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_listeMouseClicked
    // TODO add your handling code here:
    try {

        if (tbl_liste.getSelectedRow() < 0) {
            return;
        }

        Path gelen = (Path) dtm.getValueAt(tbl_liste.getSelectedRow(), 0);

        if (Files.isDirectory(Paths.get(txt_path.getText() + gelen.getFileName()), LinkOption.NOFOLLOW_LINKS)) {
            txt_path.setText(txt_path.getText() + gelen.getFileName() + "\\");
        }
    } catch (Exception e) {
    }

    listele();
}
项目:mux2fs    文件:UnixFileStatImpl.java   
@Override
public UnixFileStat stat(Path path)
        throws IOException {
    Map<String, Object> map = Files.readAttributes(path, "unix:*", LinkOption.NOFOLLOW_LINKS);
    setDev((long) map.get("dev"));
    setIno((long) map.get("ino"));
    setLinks((int) map.get("nlink"));
    setMode((int) map.get("mode"));
    setUid((int) map.get("uid"));
    setGid((int) map.get("gid"));
    setRdev((long) map.get("rdev"));
    long size = (long) map.get("size");
    setSize(size);
    setBlkSize(BLK_SIZE);
    setBlocks(size / 512 + 1); // Fake it till you make it
    setAccessTime(getInstant(map, "lastAccessTime"));
    setModificationTime(getInstant(map, "lastModifiedTime"));
    setInodeTime(getInstant(map, "ctime"));
    return this;
}
项目:OpenJSharp    文件:PathFileObject.java   
@Override
public boolean isNameCompatible(String simpleName, Kind kind) {
    simpleName.getClass();
    // null check
    if (kind == Kind.OTHER && getKind() != kind) {
        return false;
    }
    String sn = simpleName + kind.extension;
    String pn = path.getFileName().toString();
    if (pn.equals(sn)) {
        return true;
    }
    if (pn.equalsIgnoreCase(sn)) {
        try {
            // allow for Windows
            return path.toRealPath(LinkOption.NOFOLLOW_LINKS).getFileName().toString().equals(sn);
        } catch (IOException e) {
        }
    }
    return false;
}
项目:i_stolbov    文件:CommandFactoryServer.java   
/**
 * execute.
 * @param cmd - cmd
 * @throws IOException - IOException
 */
@Override
public void execute(Command cmd) throws IOException {
    Path filePath = workPath.resolve(cmd.getParam()).normalize();
    if (Files.exists(filePath, LinkOption.NOFOLLOW_LINKS)
            && !Files.isDirectory(filePath) && Files.isReadable(filePath)) {
        dataOutputStream.writeUTF(SUCCESS);
        dataOutputStream.flush();

        WritableByteChannel wbc = Channels.newChannel(dataOutputStream);
        FileInputStream fis = new FileInputStream(filePath.toString());
        fis.getChannel().transferTo(0, Long.MAX_VALUE, wbc);
        wbc.close();
    } else {
        dataOutputStream.writeUTF(ERROR);
        dataOutputStream.flush();
    }
}
项目:i_stolbov    文件:CommandFactoryClient.java   
/**
 * execute.
 * @param cmd - cmd
 * @throws IOException - IOException
 */
@Override
public void execute(Command cmd) throws IOException {
    Path filePath = Paths.get(cmd.getParam());
    if (Files.exists(filePath, LinkOption.NOFOLLOW_LINKS)
            && !Files.isDirectory(filePath) && Files.isReadable(filePath)) {

        System.out.println("Uploading...");

        ObjectOutputStream oos = new ObjectOutputStream(outputStream);
        oos.writeObject(cmd);
        oos.flush();

        WritableByteChannel rbc = Channels.newChannel(new DataOutputStream(outputStream));
        FileInputStream fis = new FileInputStream(cmd.getParam());
        fis.getChannel().transferTo(0, Long.MAX_VALUE, rbc);
        rbc.close();

        System.out.println("Done.");
    } else {
        System.out.println("Error. Please try again.");
    }
}
项目:fdt    文件:FDTSession.java   
private static String getFileListEntry(File fileInDir) {

        StringBuilder sb = new StringBuilder();
        try {
            PosixFileAttributes fa = Files.readAttributes(fileInDir.toPath(), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
            sb.append(fa.isDirectory() ? "d" : fa.isSymbolicLink() ? "l" : fa.isRegularFile() ? "f" : "-");
            sb.append(fileInDir.canRead() ? "r" : "-");
            sb.append(fileInDir.canWrite() ? "w" : "-");
            sb.append(fileInDir.canExecute() ? "x" : "-");
            sb.append("\t");
            sb.append(fa.owner());
            sb.append(fa.owner().getName().length() < 4 ? "\t\t" : "\t");
            sb.append(fa.group());
            sb.append(fa.group().getName().length() < 4 ? "\t\t" : "\t");
            sb.append(fa.size());
            sb.append(String.valueOf(fa.size()).length() < 4 ? "\t\t" : "\t");
            sb.append(fa.lastModifiedTime().toString());
            sb.append("\t");
            sb.append(fa.isDirectory() ? fileInDir.getName() + "/" : fileInDir.getName());
        } catch (IOException e) {
            logger.log(Level.WARNING, "Failed to get file attributes", e);
        }
        logger.info(sb.toString());
        return sb.toString();
    }
项目:openjdk-jdk10    文件:JrtFileSystem.java   
static boolean followLinks(LinkOption... options) {
    if (options != null) {
        for (LinkOption lo : options) {
            Objects.requireNonNull(lo);
            if (lo == LinkOption.NOFOLLOW_LINKS) {
                return false;
            } else {
                throw new AssertionError("should not reach here");
            }
        }
    }
    return true;
}
项目:openjdk-jdk10    文件:PollingWatchService.java   
PollingWatchKey(Path dir, PollingWatchService watcher, Object fileKey)
    throws IOException
{
    super(dir, watcher);
    this.fileKey = fileKey;
    this.valid = true;
    this.tickCount = 0;
    this.entries = new HashMap<Path,CacheEntry>();

    // get the initial entries in the directory
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path entry: stream) {
            // don't follow links
            long lastModified =
                Files.getLastModifiedTime(entry, LinkOption.NOFOLLOW_LINKS).toMillis();
            entries.put(entry.getFileName(), new CacheEntry(lastModified, tickCount));
        }
    } catch (DirectoryIteratorException e) {
        throw e.getCause();
    }
}
项目:dremio-oss    文件:PathUtils.java   
/**
 * Check if the provided path is a directory and is readable/writable/executable
 *
 * If the path doesn't exist, attempt to create a directory
 *
 * @param path the path to check
 * @throws IOException if the directory cannot be created or is not accessible
 */
public static void checkWritePath(String path) throws IOException {
  java.nio.file.Path npath = new File(path).toPath();

  // Attempt to create the directory if it doesn't exist
  if (Files.notExists(npath, LinkOption.NOFOLLOW_LINKS)) {
    Files.createDirectories(npath);
    return;
  }

  if (!Files.isDirectory(npath)) {
    throw new IOException(format("path %s is not a directory.", npath));
  }

  if (!Files.isReadable(npath)) {
    throw new IOException(format("path %s is not readable.", npath));
  }

  if (!Files.isWritable(npath)) {
    throw new IOException(format("path %s is not writable.", npath));
  }

  if (!Files.isExecutable(npath)) {
    throw new IOException(format("path %s is not executable.", npath));
  }
}
项目:MinecraftServerSync    文件:ServerSynchronizer.java   
private static void deleteFile(Path pathToDelete) {
    if (!Files.exists(pathToDelete, LinkOption.NOFOLLOW_LINKS)) {
        return;
    }

    if (Files.isDirectory(pathToDelete)) {
        deleteDirectory(pathToDelete);
    } else {
        try {
            Files.delete(pathToDelete);
        } catch (IOException e) {
            LOGGER.warn("Could not delete file {}", pathToDelete);
            LogUtil.stacktrace(LOGGER, e);
        }
    }
}
项目:Camel    文件:FileProducerChmodOptionTest.java   
private void runChmodCheck(String routeSuffix, String expectedPermissions) throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:chmod" + routeSuffix);
    mock.expectedMessageCount(1);
    String testFileName = "chmod" + routeSuffix + ".txt";
    String fullTestFileName = TEST_DIRECTORY + testFileName;
    String testFileContent = "Writing file with chmod " + routeSuffix + " option at " + new Date();
    mock.expectedFileExists(fullTestFileName, testFileContent);

    template.sendBodyAndHeader("direct:write" + routeSuffix, testFileContent, Exchange.FILE_NAME, testFileName);

    File f = new File(fullTestFileName);
    Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(f.toPath(), LinkOption.NOFOLLOW_LINKS);
    assertEquals(expectedPermissions, PosixFilePermissions.toString(permissions));
    assertEquals(expectedPermissions.replace("-", "").length(), permissions.size());

    assertMockEndpointsSatisfied();
}
项目:carbon-identity-mgt    文件:FileUtil.java   
public static <T> void writeConfigFiles(Path file, Object data)
        throws IdentityRecoveryException {

    if (Files.exists(file, new LinkOption[0])) {
        try {
            CustomClassLoaderConstructor constructor =
                    new CustomClassLoaderConstructor(FileUtil.class.getClassLoader());
            Yaml yaml = new Yaml(constructor);
            yaml.setBeanAccess(BeanAccess.FIELD);
            try (Writer writer = new OutputStreamWriter(new FileOutputStream(file.toFile()),
                                                        StandardCharsets.UTF_8)) {
                yaml.dump(data, writer);
            }
        } catch (IOException e) {
            throw new IdentityRecoveryException(
                    String.format("Error in reading file %s", new Object[] { file.toString() }), e);
        }
    } else {
        throw new IdentityRecoveryException(
                String.format("Configuration file %s is not available.", new Object[] { file.toString() }));
    }
}
项目:java-cloud-filesystem-provider    文件:CloudPathTest.java   
@Test
public void testToRealPathWillReturnThePathIfTheFileExists() throws IOException {
    final CloudFileSystem fs = context.mock(CloudFileSystem.class);
    final CloudFileSystemProviderDelegate fsProvider = context.mock(CloudFileSystemProviderDelegate.class);
    final String container = "blah";
    final String filePath = "fah/wah/woo/hah/plank.txt";
    final CloudPath cp = new CloudPath(fs, true, "/" + container + "/" + filePath);

    context.checking(new Expectations() {{
        allowing(fs).provider();
        will(returnValue(fsProvider));

        atLeast(1).of(fsProvider).checkAccess(cp);

        atMost(1).of(fsProvider).readAttributes(
                with(cp), with(any(Class.class)), with(any(LinkOption[].class)));
        will(returnValue(null));
    }});

    Assert.assertEquals(cp, cp.toRealPath());
}
项目:java-cloud-filesystem-provider    文件:CloudPathTest.java   
@Test
public void testToRealPathWillReturnThePathForARootContainer() throws IOException {
    final CloudFileSystem fs = context.mock(CloudFileSystem.class);
    final String container = "blah";
    final CloudFileSystemProviderDelegate fsProvider = context.mock(CloudFileSystemProviderDelegate.class);
    final CloudPath cp = new CloudPath(fs, true, "/" + container);

    context.checking(new Expectations() {{
        allowing(fs).provider();
        will(returnValue(fsProvider));

        atLeast(1).of(fsProvider).checkAccess(cp);

        atMost(1).of(fsProvider).readAttributes(
                with(cp), with(any(Class.class)), with(any(LinkOption[].class)));
        will(returnValue(null));
    }});

    Assert.assertEquals(cp, cp.toRealPath());
}
项目:lookaside_java-1.8.0-openjdk    文件:PathFileObject.java   
@Override
public boolean isNameCompatible(String simpleName, Kind kind) {
    simpleName.getClass();
    // null check
    if (kind == Kind.OTHER && getKind() != kind) {
        return false;
    }
    String sn = simpleName + kind.extension;
    String pn = path.getFileName().toString();
    if (pn.equals(sn)) {
        return true;
    }
    if (pn.equalsIgnoreCase(sn)) {
        try {
            // allow for Windows
            return path.toRealPath(LinkOption.NOFOLLOW_LINKS).getFileName().toString().equals(sn);
        } catch (IOException e) {
        }
    }
    return false;
}
项目:iofabric    文件:FieldAgent.java   
/**
 * reads json data from file and compare data checksum
 * if checksum failed, returns null
 * 
 * @param filename - file name to read data from
 * @return JsonArray
 */
private JsonArray readFile(String filename) {
    try {
        if (!Files.exists(Paths.get(filename), LinkOption.NOFOLLOW_LINKS))
            return null;

        JsonReader reader = Json.createReader(new FileReader(new File(filename)));
        JsonObject object = reader.readObject();
        reader.close();
        String checksum = object.getString("checksum");
        JsonArray data = object.getJsonArray("data");
        if (!checksum(data.toString()).equals(checksum))
            return null;
        long timestamp = object.getJsonNumber("timestamp").longValue();
        if (lastGetChangesList == 0)
            lastGetChangesList = timestamp;
        else
            lastGetChangesList = Long.min(timestamp, lastGetChangesList);
        return data;
    } catch (Exception e) {
        return null;
    }
}
项目:MSFTBX    文件:FileListing.java   
private void findFiles(Path path, List<Path> matching, LinkOption[] options, int recursionLevel) {
    if (recursionLevel > MAX_RECURSION_DEPTH)
        return; // safety net
    try {
        DirectoryStream<Path> paths = Files.newDirectoryStream(path);
        for (Path p : paths) {
            if (Files.isDirectory(p, options)) {
                if (includeDirectories && matches(p))
                    matching.add(p);
                findFiles(p, matching, options, recursionLevel);
            } else {
                if (includeFiles && matches(p))
                    matching.add(p);
            }
        }
    } catch (IOException e) {
        log.error("Could not list files in directory '{}'", path.toString());
    }
}
项目:quadracoatl    文件:ResourceManager.java   
public void gatherResources(ResourceType type, Path path, Path baseDirectory) {
    try (DirectoryStream<Path> children = Files.newDirectoryStream(path)) {
        for (Path child : children) {
            if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) {
                gatherResources(type, child, baseDirectory);
            } else if (Files.isRegularFile(child, LinkOption.NOFOLLOW_LINKS)) {
                String key = createKey(child.subpath(baseDirectory.getNameCount(), child.getNameCount()));
                Resource resource = createResource(type, key, child);

                addResource(resource, child);
            }
        }
    } catch (IOException e) {
        LOGGER.error("Failed to read \"", type, "\" from \"", path.toAbsolutePath(), "\".", e);
    }
}
项目:quadracoatl    文件:Mod.java   
protected void readInfo() {
    Path propertiesPath = Paths.get(directory.toString(), MOD_PROPERTIES_FILE);

    if (Files.exists(propertiesPath, LinkOption.NOFOLLOW_LINKS)) {
        Configuration info = new Configuration(propertiesPath);

        name = sanitizeName(info.getString("name", directory.getName(directory.getNameCount() - 1).toString()));
        displayName = info.getString("displayName", name);
        requires = Collections.unmodifiableList(info.getList("requires", " "));
    } else {
        name = sanitizeName(directory.getName(directory.getNameCount() - 1).toString());
        displayName = name;
        requires = Collections.emptyList();
    }

    gatherResources();
}
项目:mycore    文件:MCRDirectoryStream.java   
@SuppressWarnings("unchecked")
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
    if (path != null) {
        MCRPath file = checkRelativePath(path);
        if (file.getNameCount() != 1) {
            throw new InvalidPathException(path.toString(), "'path' must have one name component.");
        }
    }
    checkClosed();
    if (type == null) {
        throw new NullPointerException();
    }
    //must support BasicFileAttributeView
    if (type == BasicFileAttributeView.class) {
        return (V) new BasicFileAttributeViewImpl(this, path);
    }
    if (type == MCRMD5AttributeView.class) {
        return (V) new MD5FileAttributeViewImpl(this, path);
    }
    return null;
}
项目:meghanada-server    文件:FileSystemWatcher.java   
private void handleEvent(final WatchKeyHolder watchKeys, final WatchKey key) throws IOException {
  for (final WatchEvent<?> event : key.pollEvents()) {
    if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
      continue;
    }

    final WatchEvent<Path> watchEvent = cast(event);
    Path path = watchKeys.get(key);
    if (path == null) {
      continue;
    }

    path = path.resolve(watchEvent.context());
    if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
      if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
        watchKeys.register(path);
      }
    } else {
      // Dispatch
      FileEvent fe = toEvent(watchEvent, path);
      if (fe != null) {
        this.eventBus.post(fe);
      }
    }
  }
}
项目:meghanada-server    文件:FileUtils.java   
public static Optional<File> getClassFile(
    String path, final Set<File> sourceRoots, final File out) throws IOException {

  String outPath = out.getCanonicalPath();
  for (File rootFile : sourceRoots) {
    final String root = rootFile.getCanonicalPath();
    if (path.startsWith(root)) {
      final String src = path.substring(root.length());
      final String classFile = ClassNameUtils.replace(src, JAVA_EXT, CLASS_EXT);
      final Path p = Paths.get(outPath, classFile);
      if (Files.exists(p, LinkOption.NOFOLLOW_LINKS)) {
        return Optional.of(p.toFile());
      }
    }
  }
  return Optional.empty();
}
项目:baratine    文件:FileProviderBoot.java   
@Override
public <A extends BasicFileAttributes> A readAttributes(Path path,
                                                        Class<A> type,
                                                        LinkOption... options)
                                                            throws IOException
{
  BootJar jar = jar(path);

  if (jar == null) {
    throw new FileNotFoundException(L.l("{0} does not exist", path));
  }

  if (! type.equals(BasicFileAttributes.class)) {
    throw new UnsupportedOperationException(type.getName());
  }

  PathBase pathBase = (PathBase) path;

  return (A) new BasicFileAttributesImpl(pathBase.path(), jar);
}
项目:SonarPet    文件:RecursiveDeleteOnExitHook.java   
@Override
public void run() {
    // NOTE: Iterate backwards so last added is first deleted
    // For some reason this is important (see JDK DeleteOnExitHook(
    for (int i = toDelete.size() - 1; i >= 0; i--) {
        Path target = toDelete.get(i);
        try {
            if (Files.isDirectory(target, LinkOption.NOFOLLOW_LINKS)) {
                Files.walkFileTree(target, new RecursiveDirectoryDeleter());
            } else {
                Files.deleteIfExists(target);
            }
        } catch (IOException e) {
            //noinspection UseOfSystemOutOrSystemErr - VM is shutting down
            System.err.println("Unable to delete " + toDelete + ": " + e);
        }
    }
}
项目:xmvn    文件:TempManager.java   
private static void delete( Path path )
{
    try
    {
        if ( Files.isDirectory( path, LinkOption.NOFOLLOW_LINKS ) )
        {
            for ( Path child : Files.newDirectoryStream( path ) )
            {
                delete( child );
            }
        }

        Files.delete( path );
    }
    catch ( IOException e )
    {
        // Ignore
    }
}
项目:Yun_Shan-Common-Library    文件:StandardResourceManager.java   
protected Map<String, Resource> getFolderResources(Path dirPath, Predicate<String> nameFilter, boolean deep) {
    dirPath = this.pluginFolder.resolve(dirPath);
    if (!Files.isDirectory(dirPath, LinkOption.NOFOLLOW_LINKS)) return null;
    try {
        Map<String, Resource> allRes = Maps.newLinkedHashMap();
        ResourceFileVisitor visitor = deep ? new DeepFileVisitor(nameFilter) : new NotDeepFileVisitor(nameFilter);
        Files.walkFileTree(dirPath, visitor);
        List<Path> resPaths = visitor.getResourcePaths();
        for (Path resPath : resPaths) {
            allRes.put(this.pluginFolder.relativize(resPath).toString(), new FileResource(resPath));
        }
        if (!allRes.isEmpty()) return allRes;
    } catch (IOException e1) {
        ExceptionUtils.handle(e1);
    }
    return null;
}
项目:Yun_Shan-Common-Library    文件:StandardResourceManager.java   
@Override
public boolean writeResource(String path, InputStream resToWrite, boolean force) {
    Path resPath = this.checkResourcePath(path);
    resPath = this.pluginFolder.resolve(resPath);
    if (!force && Files.exists(resPath, LinkOption.NOFOLLOW_LINKS)) {
        return true;// 资源已存在,且参数force设为不覆盖,直接返回
    }
    try {
        File f = resPath.toFile();
        if (!f.exists()) {
            f.getParentFile().mkdirs();
            f.createNewFile();
        }
        Files.copy(resToWrite, resPath, StandardCopyOption.REPLACE_EXISTING);
        return true;
    } catch (IOException e) {
        ExceptionUtils.handle(e);
        return false;
    }
}
项目:opendata-common    文件:ConfigurationService.java   
private Configuration newLocalConfiguration( String name )
{
    LOG.log( Level.INFO, () -> "Reading local config " + name );
    Path p = Paths.get( localConfig, name + ".json" );
    if( Files.isRegularFile( p, LinkOption.NOFOLLOW_LINKS ) )
    {
        try( JsonReader r = Json.createReader( Files.newBufferedReader( p, StandardCharsets.UTF_8 ) ) )
        {
            return new MapConfiguration( MapBuilder.fromJsonObject( r.readObject() ).build() );
        } catch( IOException ex )
        {
            throw new IllegalArgumentException( ex );
        }
    }
    return EmptyConfiguration.INSTANCE;
}
项目:AdvancedServerListIcons    文件:AdvancedServerListIconsSponge.java   
private void loadConfig() {
    try {
        if (!Files.exists(defaultConfig, LinkOption.NOFOLLOW_LINKS)) {
            URL jarConfigFile = this.getClass().getResource("default.conf");
            ConfigurationLoader<CommentedConfigurationNode> loader = HoconConfigurationLoader.builder().setURL(jarConfigFile).build();
            configManager.save(loader.load());
        }

        ConfigurationNode node = configManager.load();
        node.getOptions().setShouldCopyDefaults(true);

        String user = node.getNode("jdbc-username").getString("root");
        String password = node.getNode("jdbc-password").getString("password");
        String jdbcUrl = node.getNode("jdbc-url").getString("jdbc:mysql://localhost:3306/minecraft");

        databaseManager = new DatabaseManager(jdbcUrl, user, password);
        databaseManager.connect();

        for (Map.Entry<Object, ? extends ConfigurationNode> definitionKey : node.getNode("definitions").getChildrenMap().entrySet()) {
            int priority = definitionKey.getValue().getNode("priority").getInt(1);
            ImageType type = ImageType.valueOf(definitionKey.getValue().getNode("type").getString(ImageType.OVERLAY.name()));
            String permission = definitionKey.getValue().getNode("permission").getString();
            List<String> images = definitionKey.getValue().getNode("images").getList(new TypeToken<String>() {});

            SpongeImageDetails imageDetails = new SpongeImageDetails(priority, type, permission, images);
            imageHandler.addImage(imageDetails);
        }

        configManager.save(node);
    } catch (IOException | ObjectMappingException e) {
        e.printStackTrace();
    }
}
项目:joanne    文件:Sorter.java   
private void sortByOwner(String param){
    toSort.forEach(event ->{
        try {
            UserPrincipal user = Files.getOwner(new File(event).toPath(), LinkOption.NOFOLLOW_LINKS);

            if(user.toString().equals(param)){
               sorted.add(event);
            }
        } catch (IOException ex) {

        }
    });
}
项目:alfresco-repository    文件:ImportableItem.java   
public final void setContentFile(final Path contentFile)
{
    this.contentFile = contentFile;

    if (contentFile != null)
    {
        // stat the file, to find out a few key details
        contentFileExists = Files.exists(contentFile, LinkOption.NOFOLLOW_LINKS);

        if (contentFileExists)
        {
            try
            {
                BasicFileAttributes attrs = Files.readAttributes(contentFile, BasicFileAttributes.class);

                contentFileIsReadable = Files.isReadable(contentFile);
                contentFileSize       = attrs.size();
                contentFileModified   = new Date(attrs.lastModifiedTime().toMillis());
                contentFileCreated    = new Date(attrs.creationTime().toMillis());

                if (Files.isRegularFile(contentFile, LinkOption.NOFOLLOW_LINKS))
                {
                    contentFileType = FileType.FILE;
                }
                else if (Files.isDirectory(contentFile, LinkOption.NOFOLLOW_LINKS))
                {
                    contentFileType = FileType.DIRECTORY;
                }
                else
                {
                    contentFileType = FileType.OTHER;
                }
            }
            catch (IOException e)
            {
                logger.error("Attributes for file '" + FileUtils.getFileName(contentFile) + "' could not be read.", e);
            }
        }
    }
}
项目:neoscada    文件:Executables.java   
public static void setAllExecutable ( final Path directory, final boolean state ) throws IOException
{
    Files.walkFileTree ( directory, new SimpleFileVisitor<Path> () {
        @Override
        public FileVisitResult visitFile ( final Path file, final BasicFileAttributes attrs ) throws IOException
        {
            if ( Files.isRegularFile ( file, LinkOption.NOFOLLOW_LINKS ) )
            {
                setExecutable ( file, state );
            }
            return super.visitFile ( file, attrs );
        }
    } );
}
项目:openjdk-systemtest    文件:DirectoryTools.java   
public static Path createTemporaryDirectory(Path directory) throws FileAlreadyExistsException, IOException{ 
    // Create a path under the root
    Path qualifiedPath = directoryRoot.resolve(directory);

    // Check that it doesn't already exist
    if (Files.exists(qualifiedPath, LinkOption.NOFOLLOW_LINKS)) {
        throw new FileAlreadyExistsException(qualifiedPath.toString() + " already exists");
    }

    // Create the directory structure (creates missing parental directories)
    Files.createDirectories(qualifiedPath); 
    return qualifiedPath;   
}
项目:ats-framework    文件:LocalFileSystemOperations.java   
/**
 *
 * @param filename the file name
 * @return the file user id
 * @throws FileSystemOperationException
 */
private long getUserId(
                        String filename ) {

    try {
        Integer uid = ( Integer ) Files.getAttribute( new File( filename ).toPath(), "unix:uid",
                                                      LinkOption.NOFOLLOW_LINKS );
        return uid.longValue();

    } catch( Exception e ) {
        throw new FileSystemOperationException( "Could not get UID for '" + filename + "'", e );
    }
}