2014-10-05 63 views
1

我寫了下面的代碼:Files.newDirectoryStream()拋出AccessDeniedException異常的根在Windows XP

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:\使用時拋出AccessDeniedException異常在Windows XP。我需要使用Path的Java 7實用程序。

回答

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