2009-02-03 14 views
11

de Java para principiantes:Java - Captura System.err.println o capturar una pregunta PrintStream

necesito para capturar el texto que se escribe en un archivo de impresión por un componente de tercera parte.

PrintStream está predeterminado en System.err, pero se puede cambiar a otro PrintStream.

Mirando a través de los documentos, no pude encontrar una manera fácil de dirigir el contenido de un PrintStream a un escritor/buffer de cadena.

¿Puede alguien ayudarme?

+0

¿Has probado ByteArrayOutputStream? – IAdapter

Respuesta

8
PipedOutputStream pipeOut = new PipedOutputStream(); 
PipedInputStream pipeIn = new PipedInputStream(pipeOut); 
System.setOut(new PrintStream(pipeOut)); 
// now read from pipeIn 
+3

Esto no se recomienda, la documentación indica que "los datos se escriben en un objeto PipedOutputStream por un hilo y los datos se leen del PipedInputStream conectado por algún otro hilo. Intentar utilizar ambos objetos desde un único hilo no es recomendable ya que puede bloquear el hilo." http://docs.oracle.com/javase/1.4.2/docs/api/java/io/PipedOutputStream.html – Pieter

5

Puede crear un PrintStream alrededor de cualquier otro OutputStream.

La forma más sencilla de crear uno que va a un búfer en la memoria sería:

PrintStream p = new PrintStream(new ByteArrayOutputStream()) 

entonces se podría leer y restablecer el contenido de la matriz de bytes en cualquier puntos te gusta.

Otra posibilidad sería utilizar tuberías.

InputStream third_party_output = new PipedInputStream(); 
PrintStream p = new PrintStream(new PipedOutputStream(third_party_output)); 

Luego, puede leer de la corriente third_party_output para obtener el texto escrito por la biblioteca.

3

¿Estás buscando algo como esto?

OutputStream redirect = System.err; 
    PrintStream myPrintStream = new PrintStream(redirect); 
    myPrintStream.println("hello redirect"); 

Si usted puede pasar myPrintStream a la aplicación de 3 ª parte, puede redirigir cualquier lugar que desee.

8
import java.io.*; 

public class Test { 
    public static void main(String[] args) { 
     FileOutputStream fos = null; 
     try { 
      fos = new FileOutputStream("errors.txt"); 
     } catch(IOException ioe) { 
      System.err.println("redirection not possible: "+ioe); 
      System.exit(-1); 
     } 
     PrintStream ps = new PrintStream(fos); 
     System.setErr(ps); 
     System.err.println("goes into file"); 
    } 
} 
2

utilizo la siguiente clase para registrar System.out y System.err a un conjunto de archivos (donde xxx-001.log es el más reciente) que gira. Contiene algunos métodos de llamada a la utilidad, que deberá implementar antes de que se compilen, deberían explicarse por sí mismos.

import java.io.*; 
import java.lang.reflect.*; 

public class LoggerOutputStream 
extends OutputStream 
{ 

// ***************************************************************************** 
// INSTANCE PROPERTIES 
// ***************************************************************************** 

private FileOutputStream    log=null;        // the base output stream 
private String       fnmBase,fnmExt;       // filename base, file extension 
private int        fnmCount,fnmLast;      // count for filename index, last filename used 
private int        logSize,totWritten;      // max log size, current number of bytes written 

// ***************************************************************************** 
// INSTANCE CONSTRUCTORS/INIT/CLOSE/FINALIZE 
// ***************************************************************************** 

public LoggerOutputStream(String baseFilename) throws IOException { 
    this(baseFilename,".log",2,1024000); 
    } 

public LoggerOutputStream(String baseFilename, String extension) throws IOException { 
    this(baseFilename,extension,2,1024000); 
    } 

public LoggerOutputStream(String baseFilename, String extension, int numberOfFiles, int maxFileSize) throws IOException { 
    fnmBase=baseFilename; 
    if(Character.isLetterOrDigit(fnmBase.charAt(fnmBase.length()-1))) { fnmBase=(fnmBase+"-"); } 
    fnmExt=extension; 
    if(!fnmExt.startsWith(".")) { fnmExt=('.'+fnmExt); } 
    fnmCount=numberOfFiles; 
    logSize=maxFileSize; 
    if(fnmCount>MAXLOGS) { fnmCount=MAXLOGS; } 

    fnmLast=0; 
    for(int xa=1; xa<=MAXLOGS; xa++) { 
     if(!new File(constructFilename(xa)).exists()) { 
      while((--xa)>fnmCount) { IoUtil.deleteFile(constructFilename(xa)); } 
      fnmLast=xa; 
      break; 
      } 
     } 
    log=null; 

    openFile(false); 

    if(numberOfFiles>MAXLOGS) { System.out.println("** Log File Count Limited To "+MAXLOGS); } 
    } 

public void close() throws IOException { 
    close(false); 
    } 

private void openFile(boolean ovrflw) throws IOException { 
    close(true); 

    if  (fnmLast< fnmCount) { fnmLast++;          } 
    else if(fnmLast==fnmCount) { IoUtil.deleteFile(constructFilename(fnmCount)); } 
    for(int xa=fnmLast; xa>0; xa--) { IoUtil.renameFile(constructFilename(xa-1),constructFilename(xa)); } 
    log=new FileOutputStream(constructFilename(1)); 
    totWritten=0; 
    } 

private String constructFilename(int index) { 
    return constructFilename(fnmBase,index,fnmExt); 
    } 

private synchronized void close(boolean ovrflw) throws IOException { 
    if(log!=null) { 
     log.flush(); 
     log.close(); 
     log=null; 
     } 
    } 

// ***************************************************************************** 
// INSTANCE METHODS - ACCESSORS 
// ***************************************************************************** 

public String getFilename() { 
    return constructFilename(1); 
    } 

public String getFilename(int idx) { 
    return constructFilename(idx); 
    } 

public synchronized void cycleLogFile() throws IOException { 
    openFile(true); 
    } 

// ***************************************************************************** 
// INSTANCE METHODS 
// ***************************************************************************** 

public synchronized void flush() throws IOException { 
    if(log!=null) { 
     log.flush(); 
     } 
    } 

public synchronized void write(int val) throws IOException { 
    if(log!=null) { 
     log.write(val); 
     totWritten++; 
     if(val=='\n') { 
      if(totWritten>logSize) { openFile(true); } 
      else     { log.flush(); } 
      } 
     } 
    } 

public synchronized void write(byte[] bytes) throws IOException { 
    if(log!=null) { 
     log.write(bytes); 
     totWritten+=bytes.length; 
     if(bytes.length>0 && bytes[bytes.length-1]=='\n') { 
      if(totWritten>logSize) { openFile(true); } 
      else     { log.flush(); } 
      } 
     } 
    } 

public synchronized void write(byte[] bytes, int str, int len) throws IOException { 
    if(log!=null) { 
     log.write(bytes,str,len); 
     totWritten+=len; 
     if(bytes.length>(str+len-1) && bytes[str+len-1]=='\n') { 
      if(totWritten>logSize) { openFile(true); } 
      else     { log.flush(); } 
      } 
     } 
    } 

// ***************************************************************************** 
// STATIC PROPERTIES 
// ***************************************************************************** 

static public final int     MAXLOGS=999;       // maximum log files allowed 

// ***************************************************************************** 
// STATIC METHODS 
// ***************************************************************************** 

static public String constructFilename(String bas, int idx, String ext) { 
    if(!bas.endsWith("-") && !bas.endsWith("_") && !bas.endsWith(".")) { bas=(bas+"-"); } 
    if(!ext.startsWith(".")           ) { ext=('.'+ext); } 
    return (bas+TextUtil.raZeros(idx,3)+ext); 
    } 

} /* END PUBLIC CLASS */