This question already has answers here:
Unable to create the directory error
(6 answers)
Closed 6 years ago.
I'm creating a Web Application using Java Servlets. I used JDK7, Tomcat7. I was perfectly working till I hosted local site in windows. But when I migrated to CentOS directory is Not creating.
File outputFile = new File("/Data/");
try{
if(!outputFile.exists()){
if(!outputFile.mkdir()){
throw new UnableToCreateFolderException();
}else{
outputFile = new File("/Data/" + user);
if(!outputFile.mkdir()){
throw new UnableToCreateFolderException();
}
}
}else{
outputFile = new File("/Data/" + user);
if(!outputFile.exists()){
if(!outputFile.mkdir()){
throw new UnableToCreateFolderException();
}
}
}
This is the code I used in Windows. And I tried to create "/Data" directory and give full access to user and then I tried to run it.
That path (/Data) is in the root directory, which the user you're running Tomcat as certainly shouldn't have write access to. It's always bad design to hard-code paths like this in your program; instead, you should read a property (such as myapp.homedir) and use that instead.
Just execute this command and try again,
chmod 755 /Data
chmod 777 /Data/*
Related
This question already has an answer here:
Java error in making file through console
(1 answer)
Closed 4 years ago.
I have an executable that generates some file, and I need to call this executable from a Java application. The command goes like this
Generator.exe -outputfile="path/to/file" [some other params]
It works fine on the command prompt, but running it from Java,all steps are executed but the file is not created.
I doubt the problem was that my java application is not able to crate files / directories, so I tried to create a directory as below
try {
String envp[] = new String[1];
envp[0] = "PATH=" + System.getProperty("java.library.path");
Runtime.getRuntime().exec("mkdir path/to/folder", envp);
}
catch (Exception e) {
e.printStackTrace();
}
I get the following exception, even If the directory exist
java.io.IOException: Cannot run program "mkdir":
CreateProcess error=2, The system cannot find the file specified
I also tried using java.lang.Process and java.lang.Process and I got the same exception, although the command mkdir path/to/folder works fine on the command prompt
Two points:
1) You don't need to pass in the java.library.path to the mkdir command. Mkdir expects one parameter - the directory/ies you want to created.
2) Why not use the Java File class to create the directory instead? Create a File object of the path, then call the mkdirs() function on it.
If I run my Java program in NetBeans and follow the information given in the output window to run from a command line:
To run this application from the command line without Ant, try:
java -jar "C:\Users\erdik\OneDrive\Documents\Computing Science Degree\Course Folder\Year 1\Programming 1\Assignment 2 - Year 2 Edit\assignment2\dist\assignment2.jar"
The program starts to run, but when it comes to run the following code to open a .txt file (my "database"):
System.out.println("Loading database of stored transactions...");
try
{
file = new File("TransactionDetails.txt");
inFile = new Scanner(file);
}
// if the log couldn't be found in the default program location
catch (FileNotFoundException ex)
{
System.out.println(CustomMessages.FileNotFound() +
System.getProperty("user.dir")); // display default directory
System.out.println(CustomMessages.systemExit());
System.exit(1); // the program needs the log to function as intended
}
It cannot find the .txt file and prints the default directory as the Windows System32 folder. How can I specify the location to be the Project folder as expected?
You could use an absolute path to the file instead of a relative path. e.g
file = new File("C:\Users\erdik\OneDrive\Documents\Computing Science Degree\Course Folder\Year 1\Programming 1\Assignment 2 - Year 2 Edit\assignment2\dist\TransactionDetails.txt");
inFile = new Scanner(file);
You cannot rely on the current working directory to be set to anything.
Either provide the file as a class path resource instead or ask the jvm where the class is located in the file system and locate the file relative to that.
For a read only file I would consider providing it as a resource.
I have mkdirs code like that;
File dir = new File ("/Mydir/");
if(dir.exists()==false) {
dir.mkdirs();
}
it is normal working and create directory on windows but not working on linux..
/MyDir/ is a reference to a directory inside root-dir / - you'll need root privileges to write there.
For creating a directory inside user home you could use "~/MyDir" in linux - but that will not work again in Windows.
If you're forced to use old-style File operations you could go
new File(new File(System.getProperty("user.home")), "MyDir").mkdir();
Better yet would be to invoke
Files.createDirectories(
Paths.get(System.getProperty("user.home"), "MyDir"));
This question already has answers here:
How do I programmatically change file permissions?
(12 answers)
Closed 7 years ago.
I have a piece of code using which I create a new directory.
I want to do a chmod -R 755 ./destDirectory
Way I am creating files is:
File destFile = new File("/home/destFile");
File oneFile = new File("home/destFile/1");
Check out the API documentation for the java.no.file.Files class, which has a variety of utility methods for setting attributes, permissions, and performing other actions not found in the java.io.File class.
You can use the createDirectory(...) method to set permissions upon creation, or the setPosixFilePermissions(...) method for an existing file or directory.
I have been breaking my head for two days trying to fix the file permissions for my tomcat7 server. I have a library class (.jar file included in myapp/WEB-INF) which needs to run a shell script. The library is written by me and works fine within NetBeans ie. no hassle in creating,reading and deleting files. That is because NetBeans runs the program as blumonkey(my username on my Ubuntu System). But when I import this into tomcat and run it, tomcat "executes" the command, produces no definite output, tries to check for a file(which will be generated when the script succeeds) and throws a FileNotFoundException.
More Details as follows:
Tomcat7 installed using apt-get, has its data in 2 locations - /var/lib/tomcat7 with conf and webapps folders and /usr/share/tomcat7 with the bin and lib folders
The user uploads a .zip file which is stores to /home/blumonkey/data. Rest of the program runs on the documents stored here. All new folders/files uploaded by tomcat have, obviously, tomcat7 as the owner.
I have tried things like changing the ownership to blumonkey, adding tomcat7 to blumonkey user group but none of the methods worked (Somewhere around here I probably messed up changing permissions carelessly :/ ). Apparently tomcat7 is unable to process on the files it owns.(How can this be?).
The script works when I run it in the terminal. But it doesn't work when I do a sudo -u tomcat7 script.sh, ie run it as tomcat7. It just exits with no message. I doubt that this it what is happening as I have tried to debug by redirecting the errors and outputs in ProcessBuilder but they came empty.
Any help regarding how to fix the issue and get the script running would be greatly appreciated. Please comment if you need any more info.
The code for script execution
private static void RunShellCommandFromJava(String command,String fn, String arg1,String arg2) throws Exception
{
try
{
System.out.println(System.getProperty("user.name"));
ProcessBuilder pbuilder = new ProcessBuilder("/bin/bash",command,fn,arg1,arg2);
System.out.println(pbuilder.command());
pbuilder.redirectErrorStream(true);
Process p = pbuilder.start();
p.waitFor();
}
catch(Exception ie)
{
throw ie;
}
}
The command which needs to be executed
"/bin/bash /abs/path/to/script.sh /abs/path/to/doc/in/data-folder maxpages=30 maxsearches=3"
PS : I have followed this question but it didn't help. I also tried other options like Runtime.exec(), bash,/bin/bash/ and /bin/bash/ -c, some of them don't work at all, others give no results.
Try to use Runtime and check standard error to find out what was the problem (probably permissions or paths):
// run command
String[] fixCmd = new String[] { "/bin/bash", "/abs/path/to/script.sh", "/abs/path/to/doc/in/data-folder", "maxpages=30", "maxsearches=3" };
Process start = Runtime.getRuntime().exec(fixCmd);
// monitor standard error to find out what's wrong
BufferedReader r = new BufferedReader(new InputStreamReader(start.getErrorStream()));
String line = null;
while ((line = r.readLine()) != null) {
System.out.println(line);
}