java: how to copy the currently executing file
I have a jar. I want the jar to be able to make a copy of itself while running. I understand windows may have problems with this. How would I do this, or am I over thinking it?
Edit: To explain a bit more....
I'm writing a repackagable firmware deployment system... http://code.google.com/p/heimdall-one-click/ The idea is that a ROM developer from XDA can make his own, then pack it up in a cross-platform deployable one-click packaging nearly as easily as it is to deploy the firmware.
My program takes alot of the work out by automating the tasks... I'm trying to automate packaging of the one-click deployable packaging system.... give the developers a form to fill out which will change the header information, then they select their firmware files to be deployed. I'm trying to keep i开发者_如何转开发t all in one jar.
As josh says, it would be nice if you tell why do you want to do this in order to help.
Answering only what have you post, copying the jar is just copying another file. There is the issue that it might be blocked by the OS (Windows); another issue is how do you locate it in the machine and if the user running the process has the permissions needed.
Once those two issues are solved, it is just a copy operation, the OS could not care less that if the order to copy comes from the process run from the file or from another one.
EDIT to asnwer changes in the first post.
As I told before, in the end copying a file is a OS issue. If you want to copy the current jar in Windows, then the jar must not be locked by other process so it becomes an OS question rather than a Java one.
Possible workarounds:
- The faster (but dirtiest) is to launch a .bat that does a sleep of a few seconds and then does the copy. Immediately after launching it, your close your java app. If you need to continue doing things in Java, after copying the file, the .bat launches the java app again (with the appropiate parameters).
- A variant of the previous is slightly sleazier... launch your java app from a .bat, and the first thing that .bat does is copying your jar to the PC temp directory. Be sure to document it well so your users do not get scared!
- JNI library to unlock a file. There are several programs that (Unlocker) that try to unlock files; do not know to which point it is effective or how will it affect the JVM.
I believe you can use:
File file = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
to get a reference to the path to the .JAR file.
Then you just make a copy of it:
http://download.oracle.com/javase/tutorial/essential/io/copy.html
Your operating system might not allow this, but I think it should.
精彩评论