Example usage for java.nio.file FileSystem provider

List of usage examples for java.nio.file FileSystem provider

Introduction

In this page you can find the example usage for java.nio.file FileSystem provider.

Prototype

public abstract FileSystemProvider provider();

Source Link

Document

Returns the provider that created this file system.

Usage

From source file:Main.java

public static void main(String[] args) {
    FileSystem fileSystem = FileSystems.getDefault();
    FileSystemProvider provider = fileSystem.provider();

    System.out.println("Provider: " + provider.toString());

}

From source file:Main.java

public static void main(String[] args) {
    FileSystem fileSystem = FileSystems.getDefault();
    FileSystemProvider provider = fileSystem.provider();

    System.out.println("Provider: " + provider.toString());
    System.out.println("Open: " + fileSystem.isOpen());
    System.out.println("Read Only: " + fileSystem.isReadOnly());

}

From source file:Main.java

public static void main(String[] args) {
    FileSystem fileSystem = FileSystems.getDefault();
    FileSystemProvider provider = fileSystem.provider();

    Iterable<FileStore> fileStores = fileSystem.getFileStores();
    System.out.println();/*from w  w w.ja  v a2 s.c  om*/
    System.out.println("File Stores");
    for (FileStore fileStore : fileStores) {
        System.out.println(fileStore.name());
    }

}

From source file:Test.java

public static void main(String[] args) {
    FileSystem fileSystem = FileSystems.getDefault();
    FileSystemProvider provider = fileSystem.provider();

    System.out.println("Provider: " + provider.toString());
    System.out.println("Open: " + fileSystem.isOpen());
    System.out.println("Read Only: " + fileSystem.isReadOnly());

    Iterable<Path> rootDirectories = fileSystem.getRootDirectories();
    System.out.println();/*w ww  . j  av  a 2 s .co m*/
    System.out.println("Root Directories");
    for (Path path : rootDirectories) {
        System.out.println(path);
    }

    Iterable<FileStore> fileStores = fileSystem.getFileStores();
    System.out.println();
    System.out.println("File Stores");
    for (FileStore fileStore : fileStores) {
        System.out.println(fileStore.name());
    }
}

From source file:de.codesourcery.asm.util.ASMUtil.java

/**
 * Create an ASM <code>ClassReader</code> for a given class , searching an optional classpath.
 * //from  ww  w  .  ja v  a  2  s  .  c  o  m
 * <p>If a classpath is specified, it is searched before the system class path.</p>
 * 
 * @param classToAnalyze
 * @param classPathEntries optional classpath that may contain directories or ZIP/JAR archives, may be <code>null</code>.
 * @param logger Logger used to output debug messages
 * @return
 * @throws IOException
 */
public static ClassReader createClassReader(String classToAnalyze, File[] classPathEntries, ILogger logger)
        throws IOException {
    if (!ArrayUtils.isEmpty(classPathEntries)) {
        // convert class name file-system path         
        String relPath = classToAnalyze.replace(".", File.separator);
        if (!relPath.endsWith(".class")) {
            relPath += ".class";
        }
        // look through search-path entries
        for (File parent : classPathEntries) {
            logger.logVerbose("Searching class in " + parent.getAbsolutePath());
            if (parent.isDirectory()) // path entry is a directory
            {
                final File classFile = new File(parent, relPath);
                if (!classFile.exists()) {
                    continue;
                }
                try {
                    logger.logVerbose(
                            "Loading class '" + classToAnalyze + "' from " + classFile.getAbsolutePath() + "");
                    return new ClassReader(new FileInputStream(classFile));
                } catch (IOException e) {
                    throw new IOException(
                            "Failed to load class '" + classToAnalyze + "' from " + classFile.getAbsolutePath(),
                            e);
                }
            } else if (parent.isFile()) // path entry is a (ZIP/JAR) file 
            {
                final Path archive = Paths.get(parent.getAbsolutePath());
                final FileSystem fs = FileSystems.newFileSystem(archive, null);
                final Path classFilePath = fs.getPath(relPath);

                if (Files.exists(classFilePath)) {
                    // load class from archive
                    try {
                        logger.logVerbose("Loading class '" + classToAnalyze + "' from archive "
                                + archive.toAbsolutePath());
                        InputStream in = fs.provider().newInputStream(classFilePath);
                        return new ClassReader(in);
                    } catch (IOException e) {
                        throw new IOException("Failed to load class '" + classToAnalyze + "' from "
                                + classFilePath.toAbsolutePath(), e);
                    }
                }
                continue;
            }
            throw new IOException("Invalid entry on search classpath: '" + parent.getAbsolutePath()
                    + "' is neither a directory nor JAR/ZIP archive");
        }
    }

    // fall-back to using standard classpath
    logger.logVerbose("Trying to load class " + classToAnalyze + " using system classloader.");

    try {
        return new ClassReader(classToAnalyze);
    } catch (IOException e) {
        throw new IOException("Failed to load class '" + classToAnalyze + "'", e);
    }
}

From source file:de.tiqsolutions.hdfs.HadoopFileSystemProvider.java

@Override
public void move(Path source, Path target, CopyOption... options) throws IOException {
    FileSystem fs = source.getFileSystem();
    if (!HadoopFileSystem.class.isInstance(fs))
        throw new IllegalArgumentException("source");
    if (!fs.provider().equals(target.getFileSystem().provider()))
        throw new ProviderMismatchException();
    List<Rename> renameOptions = new ArrayList<>();
    List<CopyOption> copyOptions = Arrays.asList(options);

    if (copyOptions.contains(StandardCopyOption.REPLACE_EXISTING))
        renameOptions.add(Rename.OVERWRITE);
    try {/*from  w w  w.j  a  v a 2s . co m*/
        ((HadoopFileSystem) fs).getFileContext().rename(((HadoopFileSystemPath) source).getPath(),
                ((HadoopFileSystemPath) target).getPath(),
                renameOptions.toArray(new Rename[renameOptions.size()]));
    } catch (RemoteException e) {
        rethrowRemoteException(e, source, target);

    }
}

From source file:de.tiqsolutions.hdfs.HadoopFileSystemProvider.java

@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {
    List<CopyOption> optionList = Arrays.asList(options);
    if (!optionList.contains(StandardCopyOption.REPLACE_EXISTING)) {
        if (Files.exists(target))
            throw new java.nio.file.FileAlreadyExistsException(source.toString(), target.toString(),
                    "could not copy file to destination");
    } else {/*w w  w  .  j  a  v a  2 s  . com*/
        Files.deleteIfExists(target);
    }

    FileSystem sourceFS = source.getFileSystem();
    FileSystem targetFS = target.getFileSystem();

    if (optionList.contains(HadoopCopyOption.REMOTE_COPY) && sourceFS.equals(targetFS)) {

        remoteCopy(source, target, options);
        return;

    }
    try (SeekableByteChannel sourceChannel = sourceFS.provider().newByteChannel(source,
            EnumSet.of(StandardOpenOption.READ))) {

        Set<StandardOpenOption> openOptions = EnumSet.of(StandardOpenOption.WRITE);

        if (optionList.contains(StandardCopyOption.REPLACE_EXISTING))
            openOptions.add(StandardOpenOption.CREATE);
        else
            openOptions.add(StandardOpenOption.CREATE_NEW);
        List<FileAttribute<?>> fileAttributes = new ArrayList<>();
        if (optionList.contains(StandardCopyOption.COPY_ATTRIBUTES)) {

            Set<String> sourceAttrViews = sourceFS.supportedFileAttributeViews();
            Set<String> targetAttrViews = targetFS.supportedFileAttributeViews();
            if (sourceAttrViews.contains(PosixFileAttributeViewImpl.NAME)
                    && targetAttrViews.contains(PosixFileAttributeViewImpl.NAME)) {
                PosixFileAttributes posixAttributes = sourceFS.provider().readAttributes(source,
                        PosixFileAttributes.class);
                fileAttributes.add(PosixFilePermissions.asFileAttribute(posixAttributes.permissions()));
            }

            if (sourceAttrViews.contains(HadoopFileAttributeViewImpl.NAME)
                    && targetAttrViews.contains(HadoopFileAttributeViewImpl.NAME)) {
                final HadoopFileAttributes hdfsAttributes = sourceFS.provider().readAttributes(source,
                        HadoopFileAttributes.class);
                fileAttributes.add(new FileAttribute<Long>() {
                    @Override
                    public String name() {
                        return HadoopFileAttributeViewImpl.NAME + ":blockSize";
                    }

                    @Override
                    public Long value() {
                        return hdfsAttributes.getBlockSize();
                    }
                });
                fileAttributes.add(new FileAttribute<Short>() {
                    @Override
                    public String name() {
                        return HadoopFileAttributeViewImpl.NAME + ":replication";
                    }

                    @Override
                    public Short value() {
                        return hdfsAttributes.getReplication();
                    }
                });

            }
        }

        FileAttribute<?>[] attributes = fileAttributes.toArray(new FileAttribute<?>[fileAttributes.size()]);

        try (SeekableByteChannel targetChannel = targetFS.provider().newByteChannel(target, openOptions,
                attributes)) {
            int buffSize = getConfiguration().getInt(DFSConfigKeys.DFS_STREAM_BUFFER_SIZE_KEY,
                    DFSConfigKeys.DFS_STREAM_BUFFER_SIZE_DEFAULT);
            ByteBuffer buffer = ByteBuffer.allocate(buffSize);
            buffer.clear();
            while (sourceChannel.read(buffer) > 0) {
                buffer.flip();
                targetChannel.write(buffer);
                buffer.clear();
            }

        }
        if (optionList.contains(StandardCopyOption.COPY_ATTRIBUTES)) {
            BasicFileAttributes attrs = sourceFS.provider().readAttributes(source, BasicFileAttributes.class);
            BasicFileAttributeView view = targetFS.provider().getFileAttributeView(target,
                    BasicFileAttributeView.class);
            view.setTimes(attrs.lastModifiedTime(), attrs.lastAccessTime(), attrs.creationTime());

        }

    }

}

From source file:org.cryptomator.cryptofs.CryptoDirectoryStreamTest.java

License:asdf

@Before
@SuppressWarnings("unchecked")
public void setup() throws IOException {
    filenameCryptor = cryptorProvider.createNew().fileNameCryptor();

    ciphertextDirPath = Mockito.mock(Path.class);
    FileSystem fs = Mockito.mock(FileSystem.class);
    Mockito.when(ciphertextDirPath.getFileSystem()).thenReturn(fs);
    FileSystemProvider provider = Mockito.mock(FileSystemProvider.class);
    Mockito.when(fs.provider()).thenReturn(provider);
    dirStream = Mockito.mock(DirectoryStream.class);
    Mockito.when(provider.newDirectoryStream(Mockito.same(ciphertextDirPath), Mockito.any()))
            .thenReturn(dirStream);// ww  w .j a  va2 s.  c  o  m
    longFileNameProvider = Mockito.mock(LongFileNameProvider.class);
    conflictResolver = Mockito.mock(ConflictResolver.class);
    finallyUtil = mock(FinallyUtil.class);
    Mockito.when(longFileNameProvider.inflate(Mockito.anyString())).then(invocation -> {
        String shortName = invocation.getArgument(0);
        if (shortName.contains("invalid")) {
            throw new IOException("invalid shortened name");
        } else {
            return StringUtils.removeEnd(shortName, ".lng");
        }
    });
    cryptoPathMapper = Mockito.mock(CryptoPathMapper.class);
    Mockito.when(cryptoPathMapper.resolveDirectory(Mockito.any())).then(invocation -> {
        Path dirFilePath = invocation.getArgument(0);
        if (dirFilePath.toString().contains("invalid")) {
            throw new IOException("Invalid directory.");
        }
        Path dirPath = Mockito.mock(Path.class);
        BasicFileAttributes attrs = Mockito.mock(BasicFileAttributes.class);
        Mockito.when(dirPath.getFileSystem()).thenReturn(fs);
        Mockito.when(provider.readAttributes(dirPath, BasicFileAttributes.class)).thenReturn(attrs);
        Mockito.when(attrs.isDirectory()).thenReturn(!dirFilePath.toString().contains("noDirectory"));
        return new Directory("asdf", dirPath);
    });

    Mockito.when(conflictResolver.resolveConflictsIfNecessary(Mockito.any(), Mockito.any()))
            .then(returnsFirstArg());

    doAnswer(invocation -> {
        for (Object runnable : invocation.getArguments()) {
            ((RunnableThrowingException<?>) runnable).run();
        }
        return null;
    }).when(finallyUtil).guaranteeInvocationOf(any(RunnableThrowingException.class),
            any(RunnableThrowingException.class), any(RunnableThrowingException.class));
}

From source file:org.easyrec.utils.io.TreeCopy.java

/**
* Resolve a path against another path with a potentially different
* {@link FileSystem} or {@link FileSystemProvider}
*
* <p>{@link Path#resolve(Path)} will refuse to operate if its argument is
* issued from a different provider (with a {@link
* ProviderMismatchException}); moreover, if the argument is issued from the
* same provider but is on a different filesystem, the result of the
* resolution may be on the argument's filesystem, not the caller's.</p>
*
* <p>This method will attempt to resolve the second path against the first
* so that the result is <em>always</em> associated to the filesystem (and
* therefore provider) of the first argument. For the resolution to operate,
* the following conditions must be met for {@code path2}:</p>
*
* <ul>//from  w w w  .  j a v  a2 s.  c  o  m
*     <li>if it is not absolute, it must not have a root;</li>
*     <li>if it is absolute, it must have a root, and the string
*     representation of this root must match a string representation of one
*     possible root of the first path's filesystem.</li>
* </ul>
*
* <p>If the conditions above are not satisfied, this method throws an
* {@link UnresolvablePathException} (unchecked).</p>
*
* <p>If both paths are issued from the same filesystem, this method will
* delegate to {@code path1}'s {@code .resolve()}; if they are from
* different filesystems but share the same provider, this method returns:
* </p>
*
* <pre>
*     path1.resolve(path1.getFileSystem().getPath(path2.toString()))
* </pre>
*
* <p>This means that for instance it is possible to resolve a Unix path
* against a Windows path, or the reverse, as long as the second path is
* not absolute (the root paths of both filesystems are incompatible):</p>
*
* <ul>
*     <li>resolving {@code foo/bar/baz} against {@code c:} will return
*     {@code c:\foo\bar\baz};</li>
*     <li>resolving {@code baz\quux} against {@code /foo/bar} will return
*     {@code /foo/bar/baz/quux}.</li>
* </ul>
*
* @param path1 the first path
* @param path2 the second path
* @return the resolved path
* @throws UnresolvablePathException see description
* @throws InvalidPathException {@code path2} is from a different provider,
* and one of its name elements is invalid according to {@code path1}'s
* filesystem
*
* @see FileSystem#getPath(String, String...)
* @see FileSystem#getRootDirectories()
*/
@SuppressWarnings("ObjectEquality")
private Path resolve(final Path path1, final Path path2) throws IOException {

    final FileSystem fs1 = Objects.requireNonNull(path1).getFileSystem();
    final FileSystem fs2 = Objects.requireNonNull(path2).getFileSystem();

    if (fs1 == fs2)
        return path1.resolve(path2);

    if (fs1.provider() == fs2.provider())
        return path1.resolve(fs1.getPath(path2.toString()));

    final boolean isAbsolute = path2.isAbsolute();
    final Path root2 = path2.getRoot();

    final String errmsg = isAbsolute ? "path to resolve is absolute but has no root"
            : "path to resolve is not absolute but has a root";

    // Always tricky to read an xor...
    if (isAbsolute ^ root2 != null)
        throw new IOException(errmsg);

    Path ret;

    if (isAbsolute) {
        /*
         * Check if the root of path2 is compatible with path1
         */
        final String path2Root = root2.toString();

        boolean foundRoot = false;

        for (final Path root1 : fs1.getRootDirectories())
            if (root1.toString().equals(path2Root))
                foundRoot = true;

        if (!foundRoot)
            throw new IOException("root of path to resolve " + "is incompatible with source path");

        ret = fs1.getPath(path2Root);
    } else {
        /*
         * Since the empty path is defined as having one empty name
         * component, which is rather awkward, we don't want to take the
         * risk of triggering bugs in FileSystem#getPath(); instead, check
         * that the string representation of path2 is empty, and if it is,
         * just return path1.
         */
        if (path2.toString().isEmpty())
            return path1;

        ret = path1;
    }

    for (final Path element : path2)
        ret = ret.resolve(element.toString());

    return ret;
}