Pregunta

Quiero crear diff de dos archivos. He intentado buscar el código en Java que hace, pero no encontré ningún código de código / utilidad simple para esto. Por lo tanto, pensé que si de alguna manera puedo correr Linux diferencias / sdiff comando desde mi código java y hacerlo volver un archivo que almacena el diff entonces sería grande.

Supongamos que hay dos archivos FILEA y FILEB. Debería ser capaz de almacenar su diff en un archivo llamado fileDiff través de mi código java. A continuación, ir a buscar los datos de fileDiff sería nada del otro mundo.

¿Fue útil?

Otros consejos

Se puede usar java.lang.Runtime.exec a ejecutar código simple. Esto le da una copia de un Process y se puede leer su salida normal de manera directa, sin tener que almacenar temporalmente la salida en el disco.

Por ejemplo, aquí hay un completo programa que mostrará cómo hacerlo:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class testprog {
    public static void main(String args[]) {
        String s;
        Process p;
        try {
            p = Runtime.getRuntime().exec("ls -aF");
            BufferedReader br = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null)
                System.out.println("line: " + s);
            p.waitFor();
            System.out.println ("exit: " + p.exitValue());
            p.destroy();
        } catch (Exception e) {}
    }
}

Cuando se compila y ejecuta, se da salida:

line: ./
line: ../
line: .classpath*
line: .project*
line: bin/
line: src/
exit: 0

como se esperaba.

También puede conseguir el la error corriente del error estándar de proceso, y salida corriente de la entrada estándar proceso, confusamente suficiente. En este contexto, la entrada y salida se invierten desde el mismo de la entrada de el proceso a ésta (es decir, el estándar salida del proceso).

Si desea combinar el proceso de salida estándar y el error de Java (en lugar de utilizar 2>&1 en el comando real), usted debe buscar en ProcessBuilder .

También puede escribir un archivo de script de shell e invocar ese archivo desde el código Java. como se muestra a continuación

{
   Process proc = Runtime.getRuntime().exec("./your_script.sh");                        
   proc.waitFor();
}

Escribir los comandos de Linux en el archivo de secuencia de comandos, una vez que la ejecución ha terminado se puede leer el fichero de diferencias en Java.

La ventaja de este enfoque es que puede cambiar con los comandos a cabo el cambio de código de Java.

No es necesario almacenar el diff en un tercio de archivo y luego lee desde. En lugar de hacer uso de la Runtime.exec

Process p = Runtime.getRuntime().exec("diff fileA fileB");                                                                                                                                                     
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
}

unix4j . se trata de una biblioteca en Java para Linux orden de marcha. por ejemplo, si tiene un comando como: test.txt gato | grep "Martes" | sed "s / kilogramo / kg / g" | ordenar en este programa se convertirá en: .. Unix4j.cat ( "test.txt") grep ( "Martes") sed ( "s / kilogramo / kg / g") sort ();.

Runtime run = Runtime.getRuntime();  
//The best possible I found is to construct a command which you want to execute  
//as a string and use that in exec. If the batch file takes command line arguments  
//the command can be constructed a array of strings and pass the array as input to  
//the exec method. The command can also be passed externally as input to the method.  

Process p = null;  
String cmd = "ls";  
try {  
    p = run.exec(cmd);  

    p.getErrorStream();  
    p.waitFor();

}  
catch (IOException e) {  
    e.printStackTrace();  
    System.out.println("ERROR.RUNNING.CMD");  

}finally{
    p.destroy();
}  

Puede llamar a los comandos de tiempo de ejecución de Java tanto para Windows y Linux .

import java.io.*;

public class Test{
   public static void main(String[] args) 
   {
            try
            { 
            Process process = Runtime.getRuntime().exec("pwd"); // for Linux
            //Process process = Runtime.getRuntime().exec("cmd /c dir"); //for Windows

            process.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
               while ((line=reader.readLine())!=null)
               {
                System.out.println(line);   
                }
             }       
                catch(Exception e)
             { 
                 System.out.println(e); 
             }
             finally
             {
               process.destroy();
             }  
    }
}

Esperamos que ayude ..:)

Si la apertura de ventanas

try {
        //chm file address
        String chmFile = System.getProperty("user.dir") + "/chm/sample.chm";
        Desktop.getDesktop().open(new File(chmFile));
    } catch (IOException ex) {
        Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
        {
            JOptionPane.showMessageDialog(null, "Terjadi Kesalahan", "Error", JOptionPane.WARNING_MESSAGE);
        }
    }

Las soluciones sugeridas podría optimizarse usando commons.io, el manejo de la corriente de error, y el uso de Excepciones. Yo sugeriría para envolver como éste para su uso en Java 8 o posterior:

public static List<String> execute(final String command) throws ExecutionFailedException, InterruptedException, IOException {
    try {
        return execute(command, 0, null, false);
    } catch (ExecutionTimeoutException e) { return null; } /* Impossible case! */
}

public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
    return execute(command, 0, null, true);
}

public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit, boolean destroyOnTimeout) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
    Process process = new ProcessBuilder().command("bash", "-c", command).start();
    if(timeUnit != null) {
        if(process.waitFor(timeout, timeUnit)) {
            if(process.exitValue() == 0) {
                return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
            } else {
                throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
            }
        } else {
            if(destroyOnTimeout) process.destroy();
            throw new ExecutionTimeoutException("Execution timed out: " + command);
        }
    } else {
        if(process.waitFor() == 0) {
            return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
        } else {
            throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
        }
    }
}

public static class ExecutionFailedException extends Exception {

    private static final long serialVersionUID = 1951044996696304510L;

    private final int exitCode;
    private final List<String> errorOutput;

    public ExecutionFailedException(final String message, final int exitCode, final List<String> errorOutput) {
        super(message);
        this.exitCode = exitCode;
        this.errorOutput = errorOutput;
    }

    public int getExitCode() {
        return this.exitCode;
    }

    public List<String> getErrorOutput() {
        return this.errorOutput;
    }

}

public static class ExecutionTimeoutException extends Exception {

    private static final long serialVersionUID = 4428595769718054862L;

    public ExecutionTimeoutException(final String message) {
        super(message);
    }

}

Función de Java para traer Comando Linux Resultado!

public String RunLinuxCommand(String cmd) throws IOException {

    String linuxCommandResult = "";
    Process p = Runtime.getRuntime().exec(cmd);

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    try {
        while ((linuxCommandResult = stdInput.readLine()) != null) {

            return linuxCommandResult;
        }
        while ((linuxCommandResult = stdError.readLine()) != null) {
            return "";
        }
    } catch (Exception e) {
        return "";
    }

    return linuxCommandResult;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top