Call exe file inside the jar

I am trying to call "dspdf.exe" inside the jar file where this smartpdf class exists. I plan to extract it to a temporary location and delete it when the program ends. However this does not work, any help would be appreciated.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.omg.CORBA.portable.InputStream;


public class smartpdf {
 static String url="";
 static String output="output.pdf";

public static void main(String[] args) throws IOException{
 gui mygui = new gui();//gui will call the generate function when user selects
}

 public static void generate() throws IOException{
  InputStream src = (InputStream) smartpdf.class.getResource("dspdf.exe").openStream();
  File exeTempFile = File.createTempFile("dspdf", ".exe");
  FileOutputStream out = new FileOutputStream(exeTempFile);
  byte[] temp = new byte[32768];
  int rc;
  while((rc = src.read(temp)) > 0)
      out.write(temp, 0, rc);
  src.close();
  out.close();
  exeTempFile.deleteOnExit();
  Runtime.getRuntime().exec(exeTempFile.toString()+" "+url+" "+output  );
  //Runtime.getRuntime().exec("dspdf "+url+" "+output);
 }

}

EDIT: The error I get is:

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:56)
Caused by: java.lang.ClassCastException: sun.net.www.protocol.jar.JarURLConnecti
on$JarURLInputStream cannot be cast to org.omg.CORBA.portable.InputStream
        at smartpdf.generate(smartpdf.java:18)
        at smartpdf.main(smartpdf.java:14)
        ... 5 more
+3
source share
3 answers

You are using the wrong InputStream. Change it to java.io.InputStream.

+4
source

Why are you using org.omg.CORBA.portable.InputStreaminstead of java.io.BufferedInputStream` with parameters the input stream from the resource. I mean this:

BufferedInputStream inputstream = new BufferedInputStream(smartpdf.class.getResourceAsStream(...));

Same for file stream stream: BufferedOutputStream

Do not use

class.getResource(...).openStream();

but use

class.getResourceAsStream(...);
+1

Note also (once you have solved the problem InputStream) that you must consume your child process stdout and stderr, otherwise the child process may be blocked. See this answer for more details .

0
source

Source: https://habr.com/ru/post/1717008/


All Articles