File.canWrite is not working as per expectations - java

i am trying to check whether a file is writable or not. i have changed the file permission by myself for all users. but if i try to run the program, it show "true" as a response. if i allow the permissions, then also it is showing "true".
Whats is my problem?
try
{
File file = new File("D:/myproject_log/delivery_report_edr.out");
if(!file.canWrite())
{
System.out.println("you can't write!!!");
}
else
System.out.println("you can write!!!");
}
catch(Exception e)
{
e.printStackTrace();
}

It is working fine. I copied your code and run it twice. First I got You can write, then right click on the file folder, go to properties and select read only and run the program again and I got you can't write
So as per the documentation of the method canWrite() it gave me the expected output. Please confirm your settings once again and check.

Have you tried using the java.nio.file.Files#isWritable method. as well as File#canWrite ?

I have also found that File.canWrite() cannot be trusted, especially over network drives, often returning true even though a file write will fail or vice-versa. I made my own method that actually tries to write a dummy file to the dir. That is simple to write and foolproof. Maybe they fixed it though.

I had the same issue with a file located in c:\programFiles\folder and the File.canWrite method returned true and i was getting the same exception.
when i changed the permission of write as allowed true for USER defined in security tab of Folder properties, It gave me no exception.

Related

Odd NullPointerException when using File[] in Java [duplicate]

I have a series of folders containing books on a server which I am accessing with this piece of code. I want to make each of these folders an object so I can do some work with the files inside them later on. I'm trying to use this method to return a list of the folders as Book objects.
public List<Book> getBooks(File folder){
List<Book> books = new ArrayList<Book>();
for (File f : folder.listFiles()){
if (f.isDirectory()){
System.out.println(f.getAbsolutePath() + "" + f.listFiles());
books.add(new Book(f));
}
}
return books;
}
The println statement in this block is printing, as it should, the direct path to the folder and then the memory address along with some other information. However, somewhere in the folder it is printing out null when listFiles() is called. The folder that it is doing this on is not empty. This supposedly empty folder is then passed to my class init method.
public Book(File bookFolder) {
this.bookFolder = bookFolder;
this.bookPath = bookFolder.getAbsolutePath();
System.out.println(bookFolder + " " + bookFolder.listFiles());
for (File f : bookFolder.listFiles()) {
...
}
}
The println statement in this block prints out the exact same path to the folder and then a different memory address, which is also expected. When it hits the "empty" folder it prints null for the memory address again.
Now, for the real issue, the line with the for loop is where the program crashes and throws a NullPointerException which isn't even described in the documentation for the listFiles method.
Why could this be happening? Also, why are my non-empty folders returning null?
The documentation for the listFiles() method clearly states that it "Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs."
One of the most common reasons that a directory cannot be listed is that the process lacks the right permissions. Are you running this as yourself, or in some sort of service that runs as a different user?
By the way, the File API is a great example of how bad life can be without exceptions.
For developers who have already included the following solutions :
Added the storage permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
2.The directory from you want to list the files exists.
Enabled the permission in the device you are testing in the app permission settings
BELOW CODE WILL SOLVE YOUR PROBLEM IF YOUR DEVICE SDK IS GREATER THAN OR EQUALS TO ANDROID 10(Q)
In the manifest file include this code inside tag
<application android:requestLegacyExternalStorage="true"...</application>
Let me know if your problem is solved!
I had a similar problem with dir.listfiles(); returning null for the user folder \AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\
it was the folder had by default Permissions set on "everyone" Deny all
what screwed me over i think was the fact that I never expected any Deny permission to exist there.
also for any one thats unclear on what i mean by a deny permission
when you set deny for user permissions it overrides the allow for user permissions unless you remove it and it was on a default install of windows 10 home.
For me it was caused by trailing spaces. Use variable.trim()

Cannot find CatalogManager.properties

My servlet app uses XML catalogs.
First I used org.apache.xml.resolver.tools.CatalogResolver.
It finds its configuration file CatalogManager.properties under WEB-INF/classes/.
Then I tried the same thing with com.sun.org.apache.xml.internal.resolver.CatalogManager, the version which comes with the JDK.
It doesn’t work:
Cannot find CatalogManager.properties
The spec says that this file must be somewhere on the CLASSPATH, and I suppose it is.
What should I do?
Actually, it should work, the code is the same, just repackaged:
propertyFileURI = CatalogManager.class.getResource("/"+propertyFile);
InputStream in =
CatalogManager.class.getResourceAsStream("/"+propertyFile);
if (in==null) {
if (!ignoreMissingProperties) {
System.err.println("Cannot find "+propertyFile);
// there's no reason to give this warning more than once
ignoreMissingProperties = true;
}
return;
}
What to do? Try debugging, set the breakpoint und see why it does not work.
Why do you need CatalogManager.properties anyway? If you don't, you could disable the error message with the system property xml.catalog.ignoreMissing.

How to check write permissions of a directory in java? Can we change it?

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");
}
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.)

Exception while Skeleton Tracking using openNI on pre-recorded ONI file

I am trying to run the sample openNI Skeleton Tracking application (UserTracker.java application) on a pre-recorded .oni file. I have edited the SamplesConfig.xml file to direct the input from the ONI file and not a Kinect (I don't actually have one). However, I get the following Exception. Can anybody help me here?
org.OpenNI.StatusException: Function was not implemented!
at org.OpenNI.WrapperUtils.throwOnError(WrapperUtils.java:30)
at org.OpenNI.Context.initFromXmlEx(Context.java:371)
at org.OpenNI.Context.createFromXmlFile(Context.java:36)
at UserTracker.<init>(UserTracker.java:149)
at UserTrackerApplication.main(UserTrackerApplication.java:67)
Any help will be appreciated. Thanks!
EDIT: I found a solution here, this has removed the earlier exception that I was getting, but now I get the following!
org.OpenNI.StatusException: This operation is invalid!
Anybody knows why this is happening?
I had a similar problem, I wanted to read data from a .oni file that I generated and I was getting the same issue. Now the problem is solved and maybe you solved it too, but I think it's important to share information to others that might come to this post. I found some clues in others posts by the way.
So here is the solution. The NiUserTracker sample can be used with an .oni file so I checked the code and they do the following:
xn::Player g_Player; //Global variable
// This goes in the main or another function
if (argc > 1)
{
nRetVal = g_Context.Init();
CHECK_RC(nRetVal, "Init");
nRetVal = g_Context.OpenFileRecording(argv[1], g_Player);
if (nRetVal != XN_STATUS_OK)
{
printf("Can't open recording %s: %s\n", argv[1], xnGetStatusString(nRetVal));
return 1;
}
}
This is C++ code, I work with c++. So as you can see they don't init the kinect via XML file if they want to open a recorded .oni file, they just init it via Init() method and then open a file with openFileRecording method.
If you want to open a .oni file there's no need to modify your XML, this way you can do an application that allows you to chose if you want to use a .oni or the kinect.
I hope this helps someone.
cheers.

Any sure fire way to check file existence on Linux NFS? [duplicate]

This question already has answers here:
Alternative to File.exists() in Java
(6 answers)
Closed 2 years ago.
I am working on a Java program that requires to check the existence of files.
Well, simple enough, the code make use calls to File.exists() for checking file existence. And the problem I have is, it reports false positive. That means the file does not actually exist but exists() method returns true. No exception was captured (at least no exception like "Stale NFS handle"). The program even managed to read the file through InputStream, getting 0 bytes as expected and yet no exception. The target directory is a Linux NFS. And I am 100% sure that the file being looked for never exists.
I know there are known bugs (kind of API limitation) exist for java.io.File.exists(). So I've then added another way round by checking file existence using Linux command ls. Instead of making call to File.exists() the Java code now runs a Linux command to ls the target file. If exit code is 0, file exists. Otherwise, file does not exist.
The number of times the issue is hit seems to be reduced with the introduction of the trick, but still pops. Again, no error was captured anywhere (stdout this time). That means the problem is so serious that even native Linux command won't fix for 100% of the time.
So there are couple of questions around:
I believe Java's well known issue on File.exists() is about reporting false negative. Where file was reported to not exist but in fact does exist. As the API does not throws IOException for File.exists(), it choose to swallow the Exception in the case calls to OS's underlying native functions failed e.g. NFS timeout. But then this does not explain the false positive case I am having, given that the file never exist. Any throw on this one?
My understanding on Linux ls exit code is, 0 means okay, equivalent to file exists. Is this understanding wrong? The man page of ls is not so clear on explaining the meaning of exit code: Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.
All right, back to subject. Any surefire way to check File existence with Java on Linux? Before we see JDK7 with NIO2 officially released.
Here is a JUnit test that shows the problem and some Java Code that actually tries to read the file.
The problem happens e.g. using Samba on OSX Mavericks. A possible reason
is explaned by the statement in:
http://appleinsider.com/articles/13/06/11/apple-shifts-from-afp-file-sharing-to-smb2-in-os-x-109-mavericks
It aggressively caches file and folder properties and uses opportunistic locking to enable better caching of data.
Please find below a checkFile that will actually attempt to read a few bytes and forcing a true file access to avoid the caching misbehaviour ...
JUnit test:
/**
* test file exists function on Network drive replace the testfile name and ssh computer
* with your actual environment
* #throws Exception
*/
#Test
public void testFileExistsOnNetworkDrive() throws Exception {
String testFileName="/Volumes/bitplan/tmp/testFileExists.txt";
File testFile=new File(testFileName);
testFile.delete();
for (int i=0;i<10;i++) {
Thread.sleep(50);
System.out.println(""+i+":"+OCRJob.checkExists(testFile));
switch (i) {
case 3:
// FileUtils.writeStringToFile(testFile, "here we go");
Runtime.getRuntime().exec("/usr/bin/ssh phobos /usr/bin/touch "+testFileName);
break;
}
}
}
checkExists source code:
/**
* check if the given file exists
* #param f
* #return true if file exists
*/
public static boolean checkExists(File f) {
try {
byte[] buffer = new byte[4];
InputStream is = new FileInputStream(f);
if (is.read(buffer) != buffer.length) {
// do something
}
is.close();
return true;
} catch (java.io.IOException fnfe) {
}
return false;
}
JDK7 was released a few months ago. There are exists and notExists methods in the Files class but they return a boolean rather than throwing an exception. If you really want an exception then use FileSystems.getDefault().provider().checkAccess(path) and it will throw an exception if the file does not exist.
If you need to be robust, try to read the file - and fail gracefully if the file is not there (or there is a permission or other problem). This applies to any other language than Java as well.
The only safe way to tell if the file exist and you can read from it is to actually read a data from the file. Regardless of a file system - local, or remote. The reason is a race condition which can occur right after you get success from checkAccess(path): check, then open file, and you find it suddenly does not exist. Some other thread (or another remote client) may have removed it, or has acquired an exclusive lock. So don't bother checking access, but rather try to read the file. Spending time in running ls just makes race condition window easier to fit.

Categories