Other answers require starting a new process; this is a method that does not. Here are 3 class definitions that create the welcome script described in the question.
When you start XMain.main, it generates /tmp/y.jar. Then, when you run this on the command line:
java -jar /tmp/y.jar cool
He prints:
Hello darling Y! cool
Example /YMain.java
package example; import java.io.IOException; import java.io.InputStream; public class YMain { public static void main(String[] args) throws IOException {
Example /XMain.java
package example; import java.io.FileOutputStream; import java.io.IOException; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; public class XMain { public static void main(String[] args) throws IOException { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, YMain.class.getName()); JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream("/tmp/y.jar"), manifest);
Example /Util.java
package example; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class Util { public static byte[] toByteArray(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[0x1000]; while (true) { int r = in.read(buf); if (r == -1) { break; } out.write(buf, 0, r); } return out.toByteArray(); } }
source share