How to read or extract files in the src or JAR folder and execute them in the Operating System?

0

This code works for me, but when I add the program bajador.exe, inside my jar, in "/parseadores/bajador.exe", and change those lines to call the .exe from inside the jar, it does not work. Could someone help me how should I do it? I am using the windows 10 operating system at all times, and the eclipse editor. Thanks.

public void crearVideoEnCarpeta(){
    String portaPapeles = "";
    try {
        portaPapeles = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
    } catch (HeadlessException | UnsupportedFlavorException | IOException e2) {
        e2.printStackTrace();
    }

    // aqui obtengo la ruta de donde se esta ejecutando el programa
    String rutaDondeSeEjecutaProgramaDescargador = new File(".").getAbsolutePath();
    // le quito el ultimo . y ultima barra \, osea los dos ultimos elementos, restandole -2 a su longitud
    rutaDondeSeEjecutaProgramaDescargador = rutaDondeSeEjecutaProgramaDescargador.substring(0, (rutaDondeSeEjecutaProgramaDescargador.length() - 2));
    String rutaDondeCopiare = rutaDondeSeEjecutaProgramaDescargador + "\carpeta" + "\videos";

    // antigua linea:
    //String rutaDondeDebeDeEstar = rutaDondeSeEjecutaProgramaDescargador + "\carpeta\bajador.exe " + "-o " + "\"" + rutaDondeCopiare + "\%(title)s-%(id)s.%(ext)s\"";
    // nueva linea:
    String rutaDondeDebeDeEstarNueva = "/parseadores/bajador.exe" + " " + "-o " + "\"" + rutaDondeCopiare + "\%(title)s-%(id)s.%(ext)s\"";

    try {
        String cmd2 = rutaDondeDebeDeEstarNueva + " " + portaPapeles;
        Runtime.getRuntime().exec(cmd2);

        JOptionPane.showMessageDialog(null, cmd2);
        UIManager.put("OptionPane.minimumSize", new Dimension(262, 90));

    } catch (IOException ioe) {
        System.out.println(ioe);
    }
}
    
asked by tuxero 25.12.2018 в 23:52
source

1 answer

0

In this case, what you want to do is to execute a .exe that is within .jar , a .jar file is a compressed file, which the OS can not execute files directly.

It is therefore necessary that you first extract the .exe to a Path that the OS can execute. for this, the Class java.lang.Class and its method are used getResourceAsStream() to get a InputStream from which we can read the contents of the file within the .jar to a Dirrecion that OS can execute, in the following example, it is used java.nio.file.Files.copy() to copy the contents of the file from the resource in the jar To a Temporary File:

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NewMain {

    /*extracts the resourse from the classpath to a temporal File on the OS tmp Folder.*/
    private static Path extractPayload(String resoursepath, String Filename, String extension) throws IOException {
        InputStream resourceStream = NewMain.class.getResourceAsStream(resoursepath);
        Path TmporalFile = Files.createTempFile(Filename, extension);
        Files.copy(resourceStream, TmporalFile, StandardCopyOption.REPLACE_EXISTING);
        return TmporalFile;
    }

    public static void main(String[] args) {
        try {
            Path tmpfile = extractPayload("/resources/payload.exe", "bajador", ".exe");
            //imprima el Absolute Path. de donde esta el archivo temporal. 
            System.out.println(tmpfile.toAbsolutePath().toString());
            ProcessBuilder proc = new ProcessBuilder(tmpfile.toAbsolutePath().toString(), "-o", "param2", "param3", "param etc...");
            //redirija le input y output al Standar de Java. 
            proc.redirectOutput(ProcessBuilder.Redirect.INHERIT);
            proc.redirectInput(ProcessBuilder.Redirect.INHERIT);

            Process pross = proc.start();
            //corra el .exe y espere a que termine
            pross.waitFor();
            //elimine el archivo temporal.
            if(Files.deleteIfExists(tmpfile))System.out.println("File Deleted.");
        } catch (IOException|InterruptedException ex) {
            Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Now my project looks something like this:

and the output:

run:
C:\Users\silencio\AppData\Local\Temp\bajador6041025182399461009.exe
//output del app
//output del app
File Deleted.
BUILD SUCCESSFUL (total time: 7 seconds)
    
answered by 26.12.2018 / 06:25
source