So I have a program that runs something like the following
public class SHandler extends Handler {
File lmpFile;
Down later in the program:
lmpFile = new File("Stuff.zip"); // This should create a file called "stuff.zip" in the present directory
OutputStream fos = new FileOutputStream(lmpFile); // Fill the file with whatever
Then from my main I call
S.SHandler SpecialSH = new S.SHandler(args);
//use the object for whatever
SpecialSH.delFile();
Delfile is made like this and is a method inside the class:
public void delFile() {
lmpFile.deleteOnExit();
lmpXMLFile.deleteOnExit();
}
To my knowledge this program works right on my local machine (Windows 7 Enterprise), however on our development box when I run this it's tossing a LOT of files that the program pulls all over the place. The execution path is /usr/data/dev/Handler and it's putting "stuff.zip" (and the files extracted from it) in /etc/cron.d and despite trying to remove them I am unable to.
Note This program is being called via a bash script which is invoked by a cron job on a machine running RHEL6. Anyone able to help this would get my undying love and appreciation.
Edit: The bash script is simply:
export JAVA_HOME=/usr/data/java/current
export PATH=$JAVA_HOME/bin:$PATH
/usr/data/java/current/bin/java -jar /usr/data/dev/Handler/Handler.jar
Tl;DR: File runs fine on windows, when RHEL6 calls a cron, files end up where they shouldn't. How can I make my program handle this?
It looks like the working directory is /etc/cron.d/ (executable path is different).
Relative paths (when using java.io.File), are relative to the working directory. If you want your files placed in a different directory, use absolute file paths: /path/to/stuff.zip (note the leading slash).
Perhaps these files are not closed, when delete occurs, or perhaps, an other program use them ?
Related
I create a .jar file on my local computer (with ant/eclipse) then upload it to a server (foo/usr/share/java). I want my .jar file to read in a file called "example.txt". Where on my server do I need to save "example.txt" so that this happens? Alternatively, how should I alter the filepath in my code? I am happy hardcoding this one filepath as neither the file nor filepath will change. Thanks!
If you running your application at console, then save your text file at current folder. If your application works inside application server, then file will be searched in current folder of application server.
Best way to open exact file you need - use program argument.
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
This array is the mechanism through which the runtime system passes information to your application. For example:
java MyApp arg1 arg2
Each string in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it.
If you supply a relative pathname, it is relative to the user's current working directory when he executed the .jar file. If you provide an absolute filename, job done.
You should put the file in the same directory as your .jar file and your program should find it, but as chrylis mentioned, a command-line argument is the best.
I have made a java application that sometimes should call a batch file in order to move a video from a folder to another. The batch file is in the same directory of the main class of the project (ProjectName\src\move.bat).
I got the path of the batch file through the instruction:
String pathMoveBat = new java.io.File("src\\move.bat").getAbsolutePath();
and I use the code below (which is called by pressing a button in the application) to call that file:
Process move = Runtime.getRuntime().exec(pathMoveBat+" "+username+" "+dateFormat.format(currentDate)+" "+i+"");
Basically, when I click on the button nothing happen and seems that Windows cannot find the file move.bat.
Is there any other way to call that file from a jar?
There are some points you need to understand before make it to work
In order to execute a batch file you need an external program like command prompt(cmd).
You need to know the location of batch file. Here in your case you are placing it under the src folder which will not available when you generate the jar. Since the src is a source folder so the batch should be copied to bin/dist/classes folder (output as per the IDE or project settings).
While executing the process using Runtime make sure to provide relevant argument separated with spaces. Here you are passing username and current date and i.
Once you have executed the batch file using Runtime.exec get the Process.getInputStream to catch the output if successfully executed. You will also need Process.getErrorStream to check if you have any error while executing the batch file.
Last but not least close the streams, Process.getInputStream().close(); Process.getOutputStream().close(); Process.getErrorStream().close();
Runtime.getRuntime().exec("cmd /c move.bat "+username+" "+dateFormat.format(currentDate)+" "+i+"");
Switch to ProcessBuilder if you can, its better :https://stackoverflow.com/a/10723391/1129313
I am trying to get the current users path in a giant command line application that has multiple dependencies. Every time a "." is used, it gives me the application path (where the jar exists), rather than the current user path(where the call is being made).
So, when this is ran:
File file = new File(".");
System.out.println(file.getCanonicalPath());
Gives me the path that the application exists in.
But when I create a separate small application, and use the same code. Call the jar from a different directory, it gives the current user path.
I am using JSAP command line parser for the command line arguments, its acting the same way. How can this be solved? I want my big application to get the current user path, not application path.
What would cause them to behave differently?
I think you'll find that the batch file (/shell script) which launches your "big application" is changing directory to the main jar file's directory before kicking off Java, which is why your simple test application returns the user's working directory for new File(".") while the big app returns the jar file's directory.
Try storing the user's CWD early in the batch file and then passing it to Java:
set savedcwd=%cd%
... later on ...
java "-Dsavedcwd=%savedcwd%"
then in your application
String savedcwd = System.getProperty("savedcwd");
http://www.mindspring.com/~mgrand/java-system-properties.htm
you want "user.home" property, like
System.getProperty("user.home");
String currentDir = new File(".").getAbsolutePath();
OR
System.getProperty("user.dir")
1) As stated above, if you want to get "current directory", one way is to use File(".").getAbsolutePath()
2) If you want to get the user's $PATH variable (or any environment variable), use System.getenv():
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html
I try to read a .txt file line by line in my code, which I placed it just right under the /src/ directory, when I run it with test case or with static void main, the path output is correct. However, when I run the application with Tomcat server, the app root path points to where I download my Eclipse - D:\eclipse\..., while the correct path should be D:\workspace\myproject\src\. Then, of course, it can never find the file.
Below is my code:
String workDir = System.getProperty("user.dir");
String file = "numFile.txt";
File myFile = new File(workDir + file);
String userPath = myFile.getPath();
So, my questions are:
(this maybe dumb) Where should we normally place a text file?
How can I change [System.getProperty("user.dir");], so it will point to my project workspace?
Thank you!
Sharon
regarding to your reply:
add following arguments -Duser.home='Your Path' make sure you add -D at the begining of your system variable. And this variable you can put in the VM Arguments box provided under arguments tab when you Open the Launch Configuration when using tomcat server.
I cannot find the place you are talking about. Is it in Eclipse or Tomcat directory?
thanks
Try File myFile = new File(workDir, file);
The short answer is that you can't change a running application's current working directory in Java; see Changing the current working directory in Java?
Setting the user.dir property won't work, because that doesn't affect the actual current directory that the OS uses when resolving pathnames for the application.
Setting the -Duser.dir on the command line won't work either. Rather, you have to:
if you are launching using a script, cd to the relevant directory before running the application,
if you are launching using a ProcessBuilder, set the working directory using the directory(File) method, or
if you are using an Eclipse launcher, set the "Working Directory" in the launch configuration.
Finally, what you are trying to do is (IMO) a bad idea:
Some folks write Tomcat and webapp config files on the assumption that Tomcat's current directory is the default location; e.g. $CATALINA_HOME/bin. (This is wrong ... but your hack will break it.)
When your application goes into production, you won't want to be referring back to some development sandbox.
A better approach is to do something along the lines of #Eng.Fouad's answer.
OK! I got it!
Yes,
File myFile = new File(workDir + "/" + file);
is the way to go.
and I edit the tomcat argument in Eclipse IDE. (Run -> Run Config... -> Apache Tomcat -> [Click] Tomcat vX Server -> at the right screen, click "Argument" -> Working directory section -> I change to Other and specify my actual working directory.)
It's just wierd that even I run tomcat Not by eclipse IDE, but Dos cmd and even deploy to server, it still apply the working directory as D:\Eclipse. But change the working directory worked anyway.
To read files from the root of the classpath use (eclipse automatically copies any non java file from src to classes):
this.getClass().getClassLoader().getResourceAsStream("filename.txt");
So you don't have to mess with the current folder at all.
try not to change the system properties, instead, add one more parameter into the system properties.
For Eg. add following arguments -Duser.home='Your Path' make sure you add -D at the begining of your system variable. And this variable you can put in the VM Arguments box provided under arguments tab when you Open the Launch Configuration when using tomcat server.
And if you are runing the same from some main method, then add the vairable in the run configuration, as this will maintain sactity in you code.
I am working on a small basic GUI program that gets the files from my resources and gets the names of the files and places them in a combo box. for example i just have a file inside the same package called images and trying to get the files names. the way I get the file is by using the getResoure() like so
java.net.URL url = FileDemo.class.getResource("images");
but when I try to get the files inside the directory
File urlfile = new File(url.toString());
String[] files = urlfile.list();
the first line will convert the url to string and create a file object but when I try to get the list of files inside the directory it returns a null to the array of strings.
I broke down the code and used the debugger in netbeans found out, when it did the SecurityManager check it wouldn't pass.
My question is are the files inside the project protected or there is no way to access them using the list() and listFiles() or am i doing something wrong? Also I ran the same script on my schools computer which they have windows 7 the code above worked. But when i ran it on my mac and even 2 win xp machines it just didn't work? why is that ?
I hope this makes sense i am just stuck here still a new to java
Thanks in Advance.
The class to getResource(String) is returning a URL to images but there's no guarantee that this is a file URL (beginning "file:"). If your class is embedded within a jar file this certainly won't be the case, hence why it fails in some situations and not others.
If your intention here is to actually make a portion of a file system visible to the user then I'd recommend avoiding getResource altogether, which is typically more useful when your application wishes to locate and load resources such as icons or config files.
Instead, you could use JFileChooser, which is a rich Swing component for navigating the file system and selecting files.