Java Code Examples for java.nio.file.Files.isWritable()

The following are Jave code examples for showing how to use isWritable() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: vars-annotation   File: Initializer.java   View Source Code Vote up 6 votes
private static Path createDirectory(Path path) {
    Path createdPath = path;
    if (!Files.exists(path)) {
        try {
            Files.createDirectory(path);
            if (!Files.isWritable(path)) {
                createdPath = null;
            }
        }
        catch (IOException e) {
            String msg = "Unable to create a directory at " + path + ".";
            LoggerFactory.getLogger(Initializer.class).error(msg, e);
            createdPath = null;
        }
    }
    return createdPath;
}
 
Example 2
Project: java-course   File: LsShellCommand.java   View Source Code Vote up 6 votes
/**
 * Returns formatted permissions for current file.
 * @param path Current file.
 * @return Formatted permissions.
 */
private String getPermissions(Path path) {
	char directory = '-';
	if (Files.isDirectory(path))
		directory = 'd';

	char readable = '-';
	if (Files.isReadable(path))
		readable = 'r';

	char writeable = '-';
	if (Files.isWritable(path))
		writeable = 'w';

	char executable = '-';
	if (Files.isExecutable(path))
		executable = 'x';

	return new StringBuilder().append(directory).append(readable)
			.append(writeable).append(executable).toString();
}
 
Example 3
Project: dremio-oss   File: PathUtils.java   View Source Code Vote up 6 votes
/**
 * 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));
  }
}
 
Example 4
Project: echo   File: ETLGetFile.java   View Source Code Vote up 5 votes
private Set<File> performListing(final File directory, final FileFilter filter, final boolean recurseSubdirectories) {
    Path p = directory.toPath();
    if (!Files.isWritable(p) || !Files.isReadable(p)) {
        throw new IllegalStateException("Directory '" + directory + "' does not have sufficient permissions (i.e., not writable and readable)");
    }
    final Set<File> queue = new HashSet<>();
    if (!directory.exists()) {
        return queue;
    }

    final File[] children = directory.listFiles();
    if (children == null) {
        return queue;
    }

    for (final File child : children) {
        if (child.isDirectory()) {
            if (recurseSubdirectories) {
                queue.addAll(performListing(child, filter, recurseSubdirectories));
            }
        } else if (filter.accept(child)) {
            queue.add(child);
        }
    }

    return queue;
}
 
Example 5
Project: echo   File: GetFileFromAttribute.java   View Source Code Vote up 5 votes
private Set<File> performListing(final File directory, final FileFilter filter, final boolean recurseSubdirectories) {
    Path p = directory.toPath();
    if (!Files.isWritable(p) || !Files.isReadable(p)) {
        throw new IllegalStateException("Directory '" + directory + "' does not have sufficient permissions (i.e., not writable and readable)");
    }
    final Set<File> queue = new HashSet<File>();
    if (!directory.exists()) {
        return queue;
    }

    final File[] children = directory.listFiles();
    if (children == null) {
        return queue;
    }

    for (final File child : children) {
        if (child.isDirectory()) {
            if (recurseSubdirectories) {
                queue.addAll(performListing(child, filter, recurseSubdirectories));
            }
        } else if (filter.accept(child)) {
            queue.add(child);
        }
    }

    return queue;
}
 
Example 6
Project: echo   File: ETLGetFile.java   View Source Code Vote up 5 votes
private Set<File> performListing(final File directory, final FileFilter filter, final boolean recurseSubdirectories) {
    Path p = directory.toPath();
    if (!Files.isWritable(p) || !Files.isReadable(p)) {
        throw new IllegalStateException("Directory '" + directory + "' does not have sufficient permissions (i.e., not writable and readable)");
    }
    final Set<File> queue = new HashSet<>();
    if (!directory.exists()) {
        return queue;
    }

    final File[] children = directory.listFiles();
    if (children == null) {
        return queue;
    }

    for (final File child : children) {
        if (child.isDirectory()) {
            if (recurseSubdirectories) {
                queue.addAll(performListing(child, filter, recurseSubdirectories));
            }
        } else if (filter.accept(child)) {
            queue.add(child);
        }
    }

    return queue;
}
 
Example 7
Project: JavaRushTasks   File: Solution.java   View Source Code Vote up 5 votes
public Solution(String pathToFile) {

        try {
            Path filePath = Paths.get(pathToFile);
            fileData = new ConcreteFileData(Files.isHidden(filePath), Files.isExecutable(filePath),
                    Files.isDirectory(filePath), Files.isWritable(filePath));

        } catch (Exception e) {
            fileData = new NullFileData (e);
        }
    }
 
Example 8
Project: jdk8u-jdk   File: ProxyClassesDumper.java   View Source Code Vote up 5 votes
private static void validateDumpDir(Path path) {
    if (!Files.exists(path)) {
        throw new IllegalArgumentException("Directory " + path + " does not exist");
    } else if (!Files.isDirectory(path)) {
        throw new IllegalArgumentException("Path " + path + " is not a directory");
    } else if (!Files.isWritable(path)) {
        throw new IllegalArgumentException("Directory " + path + " is not writable");
    }
}
 
Example 9
Project: OpenJSharp   File: FileHandler.java   View Source Code Vote up 5 votes
private  boolean isParentWritable(Path path) {
    Path parent = path.getParent();
    if (parent == null) {
        parent = path.toAbsolutePath().getParent();
    }
    return parent != null && Files.isWritable(parent);
}
 
Example 10
Project: jrbuilder   File: ReportUtil.java   View Source Code Vote up 5 votes
public static void storeDataSources(List<DataSource> dataSourceList) {
    Path path = Paths.get(dataSourcesStorage);
    if (!Files.isWritable(path)) {
        throw new IllegalStateException("data sources path must be writable");
    }
    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path.toAbsolutePath().toString()))) {
        for (DataSource dataSource : dataSourceList) {
            oos.writeObject(dataSource);
        }
        oos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 11
Project: openjdk-jdk10   File: FileHandler.java   View Source Code Vote up 5 votes
private  boolean isParentWritable(Path path) {
    Path parent = path.getParent();
    if (parent == null) {
        parent = path.toAbsolutePath().getParent();
    }
    return parent != null && Files.isWritable(parent);
}
 
Example 12
Project: cyberduck   File: LocalAttributesFinderFeature.java   View Source Code Vote up 5 votes
protected PathAttributes convert(final java.nio.file.Path file) throws IOException {
    final boolean isPosix = session.isPosixFilesystem();
    final PathAttributes attributes = new PathAttributes();
    final Class<? extends BasicFileAttributes> provider = isPosix ? PosixFileAttributes.class : DosFileAttributes.class;
    final BasicFileAttributes a = Files.readAttributes(file, provider, LinkOption.NOFOLLOW_LINKS);
    if(Files.isRegularFile(file)) {
        attributes.setSize(a.size());
    }
    attributes.setModificationDate(a.lastModifiedTime().toMillis());
    attributes.setCreationDate(a.creationTime().toMillis());
    attributes.setAccessedDate(a.lastAccessTime().toMillis());
    if(isPosix) {
        attributes.setOwner(((PosixFileAttributes) a).owner().getName());
        attributes.setGroup(((PosixFileAttributes) a).group().getName());
        attributes.setPermission(new Permission(PosixFilePermissions.toString(((PosixFileAttributes) a).permissions())));
    }
    else {
        Permission.Action actions = Permission.Action.none;
        if(Files.isReadable(file)) {
            actions = actions.or(Permission.Action.read);
        }
        if(Files.isWritable(file)) {
            actions = actions.or(Permission.Action.write);
        }
        if(Files.isExecutable(file)) {
            actions = actions.or(Permission.Action.execute);
        }
        attributes.setPermission(new Permission(
            actions, Permission.Action.none, Permission.Action.none
        ));
    }
    return attributes;
}
 
Example 13
Project: jdk8u-jdk   File: FileHandler.java   View Source Code Vote up 5 votes
private  boolean isParentWritable(Path path) {
    Path parent = path.getParent();
    if (parent == null) {
        parent = path.toAbsolutePath().getParent();
    }
    return parent != null && Files.isWritable(parent);
}
 
Example 14
Project: OpenJSharp   File: ProxyClassesDumper.java   View Source Code Vote up 5 votes
private static void validateDumpDir(Path path) {
    if (!Files.exists(path)) {
        throw new IllegalArgumentException("Directory " + path + " does not exist");
    } else if (!Files.isDirectory(path)) {
        throw new IllegalArgumentException("Path " + path + " is not a directory");
    } else if (!Files.isWritable(path)) {
        throw new IllegalArgumentException("Directory " + path + " is not writable");
    }
}
 
Example 15
Project: openjdk-jdk10   File: StandardDocFileFactory.java   View Source Code Vote up 4 votes
/** Return true if the file can be written. */
@Override
public boolean canWrite() {
    return Files.isWritable(file);
}
 
Example 16
Project: echo   File: GetFileBatch.java   View Source Code Vote up 4 votes
private FileFilter createFileFilter(final ProcessContext context) {
    final long minSize = context.getProperty(MIN_SIZE).asDataSize(DataUnit.B).longValue();
    final Double maxSize = context.getProperty(MAX_SIZE).asDataSize(DataUnit.B);
    final long minAge = context.getProperty(MIN_AGE).asTimePeriod(TimeUnit.MILLISECONDS);
    final Long maxAge = context.getProperty(MAX_AGE).asTimePeriod(TimeUnit.MILLISECONDS);
    final boolean ignoreHidden = context.getProperty(IGNORE_HIDDEN_FILES).asBoolean();
    final Pattern filePattern = Pattern.compile(context.getProperty(FILE_FILTER).getValue());
    final String indir = context.getProperty(DIRECTORY).evaluateAttributeExpressions().getValue();
    final boolean recurseDirs = context.getProperty(RECURSE).asBoolean();
    final String pathPatternStr = context.getProperty(PATH_FILTER).getValue();
    final Pattern pathPattern = (!recurseDirs || pathPatternStr == null) ? null : Pattern.compile(pathPatternStr);
    final boolean keepOriginal = context.getProperty(KEEP_SOURCE_FILE).asBoolean();

    return new FileFilter() {
        @Override
        public boolean accept(final File file) {
            if (minSize > file.length()) {
                return false;
            }
            if (maxSize != null && maxSize < file.length()) {
                return false;
            }
            final long fileAge = System.currentTimeMillis() - file.lastModified();
            if (minAge > fileAge) {
                return false;
            }
            if (maxAge != null && maxAge < fileAge) {
                return false;
            }
            if (ignoreHidden && file.isHidden()) {
                return false;
            }
            if (pathPattern != null) {
                Path reldir = Paths.get(indir).relativize(file.toPath()).getParent();
                if (reldir != null && !reldir.toString().isEmpty()) {
                    if (!pathPattern.matcher(reldir.toString()).matches()) {
                        return false;
                    }
                }
            }
            //Verify that we have at least read permissions on the file we're considering grabbing
            if (!Files.isReadable(file.toPath())) {
                return false;
            }

            //Verify that if we're not keeping original that we have write permissions on the directory the file is in
            if (keepOriginal == false && !Files.isWritable(file.toPath().getParent())) {
                return false;
            }
            return filePattern.matcher(file.getName()).matches();
        }
    };
}
 
Example 17
Project: jdk8u-jdk   File: CheckLockLocationTest.java   View Source Code Vote up 4 votes
/**
 * Setup all the files and directories needed for the tests
 *
 * @return writable directory created that needs to be deleted when done
 * @throws RuntimeException
 */
private static File setup() throws RuntimeException {
    // First do some setup in the temporary directory (using same logic as
    // FileHandler for %t pattern)
    String tmpDir = System.getProperty("java.io.tmpdir"); // i.e. %t
    if (tmpDir == null) {
        tmpDir = System.getProperty("user.home");
    }
    File tmpOrHomeDir = new File(tmpDir);
    // Create a writable directory here (%t/writable-dir)
    File writableDir = new File(tmpOrHomeDir, WRITABLE_DIR);
    if (!createFile(writableDir, true)) {
        throw new RuntimeException("Test setup failed: unable to create"
                + " writable working directory "
                + writableDir.getAbsolutePath() );
    }
    // writableDirectory and its contents will be deleted after the test
    // that uses it

    // Create a plain file which we will attempt to use as a directory
    // (%t/not-a-dir)
    File notAdir = new File(tmpOrHomeDir, NOT_A_DIR);
    if (!createFile(notAdir, false)) {
        throw new RuntimeException("Test setup failed: unable to a plain"
                + " working file " + notAdir.getAbsolutePath() );
    }
    notAdir.deleteOnExit();

    // Create a non-writable directory (%t/non-writable-dir)
    File nonWritableDir = new File(tmpOrHomeDir, NON_WRITABLE_DIR);
    if (!createFile(nonWritableDir, true)) {
        throw new RuntimeException("Test setup failed: unable to create"
                + " a non-"
                + "writable working directory "
                + nonWritableDir.getAbsolutePath() );
    }
    nonWritableDir.deleteOnExit();

    // make it non-writable
    Path path = nonWritableDir.toPath();
    final boolean nonWritable = nonWritableDir.setWritable(false);
    final boolean isWritable = Files.isWritable(path);
    if (nonWritable && !isWritable) {
        runNonWritableDirTest = true;
        System.out.println("Created non writable dir for "
                + getOwner(path) + " at: " + path.toString());
    } else {
        runNonWritableDirTest = false;
        System.out.println( "Test Setup WARNING: unable to make"
                + " working directory " + nonWritableDir.getAbsolutePath()
                + "\n\t non-writable for " + getOwner(path)
                +  " on platform " + System.getProperty("os.name"));
    }

    // make sure non-existent directory really doesn't exist
    File nonExistentDir = new File(tmpOrHomeDir, NON_EXISTENT_DIR);
    if (nonExistentDir.exists()) {
        nonExistentDir.delete();
    }
    System.out.println("Setup completed - writableDir is: " + writableDir.getPath());
    return writableDir;
}
 
Example 18
Project: openjdk-jdk10   File: JdepsTask.java   View Source Code Vote up 4 votes
private GenDotFile genDotFile(Path dir) throws BadArgs {
    if (Files.exists(dir) && (!Files.isDirectory(dir) || !Files.isWritable(dir))) {
        throw new BadArgs("err.invalid.path", dir.toString());
    }
    return new GenDotFile(dir);
}
 
Example 19
Project: openjdk-jdk10   File: JdepsTask.java   View Source Code Vote up 4 votes
private GenModuleInfo genModuleInfo(Path dir, boolean openModule) throws BadArgs {
    if (Files.exists(dir) && (!Files.isDirectory(dir) || !Files.isWritable(dir))) {
        throw new BadArgs("err.invalid.path", dir.toString());
    }
    return new GenModuleInfo(dir, openModule);
}
 
Example 20
Project: OpenJSharp   File: PathDocFileFactory.java   View Source Code Vote up 4 votes
/** Return true if the file can be written. */
public boolean canWrite() {
    return Files.isWritable(file);
}