View Full Version : [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.
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.Sì, è possibile.
Ecco un esempio:
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);
}
}
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 :muro: .... ho il libro "Java I/O" a casa, non l'ho ancora letto tutto tutto ma è meglio se lo rileggo bene!
vBulletin® v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.