Files.newDirectoryStream()在Windows XP中的root上引发AccessDeniedException

时间:2014-10-05 22:01:20

标签: java windows-xp java-7 access-denied

我写了以下代码:

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());
    }
}

然而,行

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

C:\上使用时,在Windows XP上引发AccessDeniedException。我需要使用Path。

来使用Java 7实用程序

1 个答案:

答案 0 :(得分:1)

使用Java-6访问文件,然后使用file.toPath()使用Java-7特定功能。

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());
    }
}