|
|
|
|
Strumenti |
03-05-2007, 10:30 | #1 |
Member
Iscritto dal: Sep 2005
Messaggi: 274
|
[Java] System.out
Ciao, volevo sapere se era possibile "clonare" il System.out.
Cioè vorrei che quando viene invocata : System.out.println("Stringa"); Mi scriva sia sullo standard output (console) che su un mio File. Grazie. |
03-05-2007, 10:56 | #2 | |
Senior Member
Iscritto dal: Nov 2005
Città: TO
Messaggi: 5206
|
Quote:
Ecco un esempio: Codice:
import java.io.*; public class Prova { public static void main (String[] args) { try { FileOutputStream fos = new FileOutputStream ("unfile.txt"); DupOutputStream dupos = new DupOutputStream (System.out, fos); PrintStream ps = new PrintStream (dupos); System.setOut (ps); System.out.println ("Questa stringa va sullo standard-output e sul file!"); ps.close (); } catch (Exception e) { e.printStackTrace (); } } } class DupOutputStream extends OutputStream { private OutputStream one; private OutputStream two; public DupOutputStream (OutputStream one, OutputStream two) { this.one = one; this.two = two; } public void close () throws IOException { one.close (); two.close (); } public void flush () throws IOException { one.flush (); two.flush (); } public void write (int b) throws IOException { one.write (b); two.write (b); } public void write (byte[] b) throws IOException { one.write (b); two.write (b); } public void write (byte[] b, int off, int len) throws IOException { one.write (b, off, len); two.write (b, off, len); } }
__________________
Andrea, SCJP 5 (91%) - SCWCD 5 (94%) |
|
03-05-2007, 11:17 | #3 |
Member
Iscritto dal: Sep 2005
Messaggi: 274
|
Grazie,
Ancora. |
03-05-2007, 12:26 | #4 |
Senior Member
Iscritto dal: Nov 2005
Città: TO
Messaggi: 5206
|
Quello di cui non sono sicuro è la ps.close(), se è giusto farla o meno (o fare diversamente).
Facendola, vengono chiusi i due stream (del file e del System.out originale). Chiudere lo stream relativo al file è corretto e sacrosanto. Non so se chiudere il System.out originale va bene. Magari alla fine si potrebbe rimettere tutto a posto, cioè salvare all'inizio il System.out originale e alla fine ripristinarlo e quindi chiudere solo lo stream del file. Sono un testone .... ho il libro "Java I/O" a casa, non l'ho ancora letto tutto tutto ma è meglio se lo rileggo bene!
__________________
Andrea, SCJP 5 (91%) - SCWCD 5 (94%) |
Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 12:28.