2009-02-03 2 views
11

자바 신참 질문 캡처 : 나는 텍스트가 제 3 자 구성 요소에 의해의 PrintStream에 기록되는 캡처해야자바 - 캡처 System.err.println을하거나의 PrintStream

합니다.

PrintStream의 기본값은 System.err이지만 다른 PrintStream으로 변경할 수 있습니다.

문서를 살펴보면 PrintStream의 내용을 문자열 작성기/버퍼로 전달하는 쉬운 방법을 찾을 수 없습니다.

누군가 도움을 줄 수 있습니까?

+0

ByteArrayOutputStream을 시도해 보셨습니까? – IAdapter

답변

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

이 문서는 "데이터가 하나의 스레드에 의해 PipedOutputStream 객체에 쓰여지고 다른 스레드에 의해 연결된 PipedInputStream에서 데이터가 읽혀 지므로 단일 스레드에서 두 객체를 모두 사용하려고 시도하는 것은 권장하지 않습니다. 실." http://docs.oracle.com/javase/1.4.2/docs/api/java/io/PipedOutputStream.html – Pieter

5

다른 OutputStream에서 PrintStream을 만들 수 있습니다.

것 메모리에 버퍼로 이동 한 만들 수있는 가장 간단한 방법 :

PrintStream p = new PrintStream(new ByteArrayOutputStream()) 

그런 다음 당신이 읽고 어떤 점을 당신이 좋아하는의 바이트 배열의 내용을 재설정 할 수 있습니다.

또 다른 가능성은 파이프를 사용하는 것입니다.

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

그럼 당신은 라이브러리에 의해 쓰여진 텍스트를 얻기 위해 third_party_output 스트림에서 읽을 수 있습니다.

3

이와 비슷한 제품을 찾고 계십니까?

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

당신이 제 3 자 응용 프로그램에 myPrintStream를 전달할 수 있다면, 당신은 어디서나 당신이 원하는 그것을 리디렉션 할 수 있습니다.

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

나는 (XXX-001.log 가장 최근의) 파일을 회전 세트에 System.out을하고 System.err에 로그 다음과 같은 클래스를 사용합니다. 여기에는 유틸리티 메서드에 대한 몇 가지 호출이 포함되어 있습니다. 유틸리티 메서드는 컴파일하기 전에 구현해야합니다.이 메서드는 자체적으로 설명해야합니다.

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 */ 
관련 문제