PDA

View Full Version : [JAVA] Linux & Console


joeykiske
26-05-2010, 18:03
Salve,
ho creato un programmino che fa girare NETSTAT su Linux e,dovrebbe,salvare il tutto in un file txt...quando eseguo il programma,NETSTAT è visibile tra i processi con top o ps ma,non viene scritto alcun file txt.

Le righe di comande che uso sono


Runtime netstat = Runtime.getRuntime();
Process p = netstat.exec("netstat -atc > prova.txt");


Il problema è che non viene generato quel file prova.txt :cry: non capisco il perchè...:eek: uso Debyan come versione...

Se eseguo,nella console (terminale),il comando 'netstat -atc > prova.txt' (senza apici) il file viene generato!! perchè con il programma questo non viene effettuato!? :cry:

Aiutoooooo!! :cry:

Grazie Anticipatamente

deadlyomen17
26-05-2010, 19:09
il metodo exec non funziona esattamente come una shell -> javaworld.com - When Runtime.exec() won't work (http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4)

ti interessa soprattutto questa parte:
Runtime.exec() is not a command line

One final pitfall to cover with Runtime.exec() is mistakenly assuming that exec() accepts any String that your command line (or shell) accepts. Runtime.exec() is much more limited and not cross-platform. This pitfall is caused by users attempting to use the exec() method to accept a single String as a command line would. The confusion may be due to the fact that command is the parameter name for the exec() method. Thus, the programmer incorrectly associates the parameter command with anything that he or she can type on a command line, instead of associating it with a single program and its arguments. In listing 4.6 below, a user tries to execute a command and redirect its output in one call to exec():

per portare l'output di netstat su un file devi usare l'inputstream del processo restituito da exec:

public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(new File("file.txt"));
Runtime r = Runtime.getRuntime();
Process p = r.exec("netstat");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while( (line = in.readLine()) != null ) {
out.println(line);
System.out.println(line);
}
}

joeykiske
14-06-2010, 16:01
Scusate per la tarda risposta..:mc: ..Grazie mille per l'aiuto! :)