Search code examples
javawindows-xpjava-7access-denied

Files.newDirectoryStream() throws AccessDeniedException on root in Windows XP


I wrote the following code:

void backupFileAttributes(Path path, BufferedWriter writer) throws IOException
{
    try
    {
        if (Files.isReadable(path))
        {
            DirectoryStream<Path> stream = Files.newDirectoryStream(path);
            for (Path entry : stream)
            {
                BasicFileAttributes attr = Files.readAttributes(entry, BasicFileAttributes.class);
                if (Files.isDirectory(entry))
                {
                    writer.append((getFileData(entry, attr)));
                    writer.newLine();
                    backupFileAttributes(entry, writer);
                }
                writer.append(getFileData(entry, attr));
                writer.newLine();
            }
        }
        else
        {
            System.out.println("Could not read directory: " + path.toAbsolutePath());
        }
    }
    catch (java.nio.file.AccessDeniedException e)
    {
        System.out.println("Access was denied on path: " + path.toAbsolutePath());
    }
}

However, the line

DirectoryStream<Path> stream = Files.newDirectoryStream(path);

Throws AccessDeniedException on Windows XP when used on C:\. I need Java 7 utilities using Path.


Solution

  • Use Java-6 for accessing the files, then use the Java-7 specific features using file.toPath().

    void backupFileAttributes(File dir, BufferedWriter writer) throws IOException
    {
        try
        {
            String[] files = dir.list();
            if (files != null)
            {
                for (String s : files)
                {
                    String path;
                    if (s.equals(".") == true)
                    {
                        path = s;
                    }
                    else
                    {
                        path = dir.getPath() + File.separator + s;
                    }
    
                    File f = new File(path);
                    if (f.canRead() != false)
                    {
                        Path p = f.toPath();
                        BasicFileAttributes attr = Files.readAttributes(p, BasicFileAttributes.class);
                        if (f.isDirectory() == true)
                        {
                            writer.append((getFileData(p, attr)));
                            writer.newLine();
                            backupFileAttributes(f, writer);
                        }
                        else if (f.isFile() == true)
                        {
                            writer.append(getFileData(p, attr));
                            writer.newLine();
                        }
                    }
                }
            }
        }
        catch (java.nio.file.AccessDeniedException e)
        {
            System.out.println("Access was denied on path: " + dir.getAbsolutePath());
        }
    }