La classe Runtime ha il metodo exec(String cmd), che avvia un processo e restituisce un oggetto Process.
L'oggetto Process ha il metodo getInputStream che ti restituisce un InputStream da cui leggere l'output prodotto.
Poi crei un file, prendi il suo FileWriter e ci scrivi dentro.
codice:
StringBuffer sb=new StringBuffer();
try {
Process diff=Runtime.getRuntime().exec("diff file1.txt file2.txt");
BufferedInputStream out=new BufferedInputStream(diff.getInputStream());
byte[] buffer=new byte[1000];
int numbytes;
while((numbytes=out.read(buffer)) != -1 ) {
sb.append(new String(buffer, 0, numbytes));
}
}
catch (IOException ioe) {
System.out.println("IOException: impossibile eseguire diff");
}
try {
output=new BufferedWriter(new FileWriter(new File("diff.txt")));
output.write(sb.toString());
}
finally {
if (output != null) output.close();
}
Oppure, molto più semplicemente, puoi usare la redirezione dell'output del sistema operativo, mandando lo standard output su file anziché su schermo.
codice:
try {
Process diff=Runtime.getRuntime().exec("diff file1.txt file2.txt > diff.txt");
}
catch (IOException ioe) {
System.out.println("IOException: impossibile eseguire diff");
}