My OS is fedora and I use the following code to create a file:
String destFile = "/var/www/html/nykkos/app/webroot/AssimilatorGenerator/Script_May6/db/"+"musics.db";
File destinationFile= new File(destFile);
if(!destinationFile.exists()) {
destinationFile.createNewFile();
}
It gives me the following exception at the line destinationFile.createNewFile()
java.io.IOException: Permission denied
Why this exception occurs and how can I overcome the same?
sudo chmod a+rwx /var/www/html/nykkos/app/webroot/AssimilatorGenerator/Script_May6/db changes the rights for all to the directory. Better look first whether chown, changing the owner/group might do. Or a combination of same group and giving the group all rights.
BTW createNewFile is seldom needed.
It is probably because the user you are running the JVM with has not the right permission to write at that path. But please post more deatils for a better answer.
You have to check owner mode and permission setting of parents directories setting. If there is no write permission in Your OS, you will get the exception.
Related
I am working on a task, which is changing the file's permission to 640 after our code exports the file to our Linux server. The same code works in our Dev server, but in our Uat server, sometimes the permission is changed to 640 successfully, sometimes the permission can not be changed, is still the default 600.
I checked the SystemOut.log, no any error for this.
My related Java code is like below:
private void exportXXXFiles() {
......
//Settings for the access permissions of the exported files
Set<PosixFilePermission> filePerms = new HashSet<PosixFilePermission>();
filePerms.add(PosixFilePermission.OWNER_READ);
filePerms.add(PosixFilePermission.OWNER_WRITE);
filePerms.add(PosixFilePermission.GROUP_READ);
try {
Path localFilePath = ......;
Files.setPosixFilePermissions(localFilePath, filePerms);
......
} catch (IOException e) {
e.printStackTrace();
}
}
I am confused why the same code works in our Dev server but not stable in our Uat server, where sometimes it works sometimes it does not work. I assume that is the environment issue, but I have no idea what the exact issue is. Who can give me some suggestions?
Thanks!
There are a few reason why changing permissions might not work. These include:
The application doesn't have permission to change permissions. With classic UNIX / Linux, you need to be the file owner or root to change an file's permissions. Then there are ACLs.
The file system might be read-only, or mounted read only.
The file system type might not support the combination of permissions you are trying to use. For example, FAT did not support execute permissions, and NTFS permissions work a bit differently. Unfortunately, when you mount a "foreign" file system type on Linux, the OS doesn't provide a way to direcrly manipulate the file system's native permissions.
It is possible that what you are trying to do is blocked by SE Linux or AppArmor or similar.
Now, some of these may result in a Java exception when you attempt to change the permission. But that is up to the OS and the file system drivers. Java can only throw an exception if the OS tells Java that the permission change attempt failed, and it can only report / interpret the reason (the errno) returned by the chmod syscall.
On a particular server (Windows 2012 server R2) I am having trouble creating a temp file. I get the following error everytime I try.
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createTempFile(Unknown Source)
etc..
The error happens everytime the following code is ran:
InputStream inputStream = portalBean.createPDF( sessionID, foCode );
Things I have tried
Changed the java.io.tmpdir variable on the fly. System.setProperty("java.io.tmpdir", "C:\\");
Added -Djava.io.tmpdir=c:\\temp to the webnetwork lax file to an unrestricted location.
I tried setting the webNetwork service to run as a specified user with rights to temp files e.g. the Administrator.
Made sure I have free disk space and I cleaned out the c:\windows\temp folder.
Made sure the tmp environment variables were set to their default values.
I also tried running the service from a command prompt which was opened with the Run As Administrator option.
And the IOException lingers still. I have another server running the same code without issue (Windows Server 2012).
Does anyone else have any Ideas of what else I can try to resolve this issue? And or any tips on how I can debug the issue more thoroughly to get a grasp of what is going on?
One tool you can use to debug this is process monitor from system internal tool kit. The step is: add a filter to only monitor your process (I think it is javaw.exe in your case), after the error happens, go through the file activities in the process monitor log, you can find how the process is finding files and which directories the process searched. If the process is searching in the wrong directory, you can find it from the log.
I just used this tool to figure out a JVM crash problem today.
Based on the description of your problem, I guess the path variable of the process is changed in the middle of your code, with another tool process explore you can view the path variable of the process, it might help.
Try and create instead a directory somewhere under your home directory:
final Path tmpdir = Paths.get(System.getProperty("user.home"), "tmp");
Files.createDirectories(tmpdir);
System.setProperty("java.io.tmpdir", tmpdir.toAbsolutePath().toString());
Then try and Files.createTempFile() in there.
Note that if Files.createDirectories() refers to an existing file which is not a directory, you'll get a FileAlreadyExistsException.
My application has multiple users and 1 superuser. I am trying to write and store a file in Linux through Java code but i get permission denied error. I used the following code:
Process process = Runtime.getRuntime().exec("/usr/bin/tiff2pdf -o /tmp/tiff_dir/temp.pdf /tmp/tiff_dir/image.tiff");
int returnCode = process.waitFor();
I get following error:
java.io.FileNotFoundException: image.tiff (Permission denied)
From my analysis, it seems that because the user does not have root permissions, i am getting this error. What is the solution to this?
You shouldn't run a command like that as a super user because it poses a security risk (i.e. if someone gained control of your java program, then they have the keys to the kingdom). Instead, you should run with lower permissions.
It looks like the issue is with access to image.tiff not with tiff2pdf. Check the owner and permissions of image.tiff.
Firstly, these two lines will not produce a java.io.FileNotFoundException: image.tiff (Permission denied):
Process process = Runtime.getRuntime().exec("/usr/bin/tiff2pdf -o temp.pdf image.tiff");
int returnCode = process.waitFor();
If for some reason, the command fail, it will return a non-zero return code will produce some output on the process's standard error (that's the convention). You can get that standard error from process.getErrorStream() (it might be worth having a look at the standard output too, just in case). If there's an issue with the file not being found there, it will not throw a FileNotFoundException like this, since Java cannot understand the expected output from your command.
EDIT, following your comment:
It was thrown from this point only and value of returnCode was 1. Also everything worked fine once i manually changed the file permissions from a root user.
That's just not possible. If your application throws an exception at either of these two lines, it will exit the normal control flow: you will not be able to read the returnCode at all.
Secondly, your should run your exec command with each argument in a String[] instead of having it all in one line, this should prevent quotation problems if file names have spaces for example.
I would also suggest using absolute paths in your command, to make sure you're working in the directories you expect. (*EDIT: * Now that you're using absolute paths, make sure your user has rwx permissions on /tmp/tiff_dir .)
To answer your question more directly, you can certainly run sudo with Runtime.exec(new String[] {"/usr/bin/sudo", ... the rest of your command ... }, but this is a bad idea, for security reasons. You'd also need to change the sudoers file to allow it without password, or find a way to pass in a password, either on the command line (definitely a security risk!) or by passing it to the input stream manually, somehow.)
Try this :
File file = new File("/opt/image.tiff");
Runtime runtime = Runtime.getRuntime();
runtime.exec(new String[] { "/bin/chmod", "777",file.getPath()});
This will execute full permission on the file.
i'm having the the post's title error when trying to write a file on a window folder , mounted on unix system. I've developed a web service which runs inside a Tomcat 6 on a linux os and need to write on a windows network folder. System administrators have mounted it on the Linux sever and have no problem to create and modify a file on it.
When i try to execute the posted code i get the following exception :
Permission denied
java.io.IOException: Permission denied
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:850)
The weird thing is that it seems to be related to the File.createNewFile method on a network folder , in fact the service can write on local file system without problems, both on debug (the pc i use to develop the service) and a tomcat folder system administrators have provided me on the linux server. The file gets created but is empty and the log entry following the create method doesn't get printed. Moreover if i use a plain outputstream to create and write the file i've no problems.
I cannot find any explanation about the exception on the web. Since i'm not very experienced with java , i'd like to understand why i'm getting this error. Am i using it in the wrong way ? Is it a bug of the library ? Do i miss to pass some parameter ?
As stated , i've solved the problem using a plain outputstream, this is a question to improve my understanding of java.
FileOutputStream fos = null;
try{
log.info(String.format("file length: %s",streamAttach.length));
log.info(String.format("check File : %s",filename));
File f = new File(filename);
if(f.exists())
...
boolean done= f.createNewFile();//here comes the exception
//nothing of the following happens
if(!done)
throw new NWSException("error creating file");
log.info(String.format("file %s creato", nomeFile));
thank you in advance for any answer
I ran into this problem recently and found that java.io.File.createNewFile() actually requires the "Change Permissions" permission (you can find this entry under Security->Advanced when checking folder permissions). Without this it will create the file and then subsequently throw an IOException.
It's deceptive because you will still be able to create files on the folder when manually testing, however createNewFile() will still fail if it doesn't have this particular permission (presumably such that it can change the permissions on the file its creating).
If you are using Netapp that shares an NTFS (CIFS) style filesystem to Unix you could be experience "NFS is not allowed to change permissions on a file in an NTFS-style security volume." (TR-3490 page 16)
Options here are to change to a unix filesystem or set the cifs.ntfs_ignore_unix_security_ops flag to on for the file system which quiches the NFS permission error.
java.io.UnixFileSystem.createFileExclusively(Native Method) opens the file with the O_EXCL and 0666 umask so I would get a EACCES, which really was a NFS3RR_ACCES
open("/net/storage01-a/filer/myfile", O_RDWR|O_CREAT|O_EXCL, 0666) Err#13 EACCES
Also you can use OutputStream to create the file, that does not use O_EXCL it seemes
It definitely not Java specific problem. If this Unix folder is mapped to your windows try to open file explorer and create file in this directory. I believe that you will get permission denied too. In this case fix this problem or ask your system administrator to help you.
Good luck!
i try to check the permission granted to a directory in linux, i mean i have a directory with permission 755
berty#berty-laptop:~$ ls -l / |grep directory
drwxr-xr-x 3 root root 4096 2011-01-10 12:33 directory
how can i read that permission with java? I've tried using FilePermission but though i have a directory with all the permissions (777) the FilePermission class always returns an exception
java.security.AccessControlException: Access denied (java.io.FilePermission /home/directory read)
at java.security.AccessController.checkPermission(AccessController.java:103)
at com.snippets.Check4DirectoryPermission.checker(Check4DirectoryPermission.java:50)
at com.snippets.Check4DirectoryPermission.main(Check4DirectoryPermission.java:70)
is there another way to do this?
java.io.File.canRead(), where the file instance is the one representing the dir
Returns:
true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise
I think you made a mistake: The ls command shows the existence of /directory, but the Java code complaints about /home/directory - which does not exist unless you have a user called directory.
From your stack trace, I assume that you are creating a FilePermission object yourself and hand it over to AccessController.checkPermission(). This is not how it is used - the FilePermission class does NOT represent the filesystem permissions and does NOT check them. It is used by Java's SecurityManager only, e.g. it looks whether the policy file contains rules that allow the application to access the file. Whether the local file system supports permissions or not is not its concern.
As Bozho suggest, you create a java.io.File() object and use the canXXX() methods to check whether you can access the folder or file.
If you need more detailed information about filesystem-level permissions on a file, you need to wait for Java 7. See the Java NIO.2 Tutorial especially the java.nio.file.attributepackage.