-1

I am using the code below, but it’s not working. The method canWrite() is not working, even if changing the rights for writing for a directory.

File file = new File(fc.getSelectedFile().getAbsolutePath());
// fc is a FileChooser object
if(f.canWrite()) 
{
  // write access
} 
else 
{
  // no write access
}

I have also tried:

try 
{
    AccessController.checkPermission(new FilePermission("/tmp/*", "read,write"));
    System.out.println("Good");
    // Has permission
}
catch (SecurityException e) 
{
// Does not have permission
System.out.println("Bad");
}
Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
mohit_pipariya
  • 67
  • 1
  • 13
  • For change the permissions Look at this link :- "http://stackoverflow.com/questions/664432/how-do-i-programmatically-change-file-permissions" – Alya'a Gamal Jan 28 '13 at 09:30

1 Answers1

1

The File.canWrite() method is behaving as its specification says it should:

Returns: true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.

(Emphasis added).

It is returning false because the object is not a file.


If you are using Java 7 (or later), one solution would be to use Files.getAttribute to retrieve the relevant attribute(s) to determine the access. Note that the attribute you use may be operating system specific. (I'm sure Google could find examples for you.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216