2011-01-25 9 views
30

次のコードを使用してSystem.outを/ dev/nullに一時的にリダイレクトしようとしましたが、動作しません。Javaでは、どうすればSystem.outをnullにしてからstdoutに戻すことができますか?

System.out.println("this should go to stdout"); 

PrintStream original = System.out; 
System.setOut(new PrintStream(new FileOutputStream("/dev/null"))); 
System.out.println("this should go to /dev/null"); 

System.setOut(original); 
System.out.println("this should go to stdout"); // This is not getting printed!!! 

誰でもアイデアはありますか?

+0

システムで両方の行が正常に表示されています。私はJava 6 update 22を使用しています。 –

+2

BTW:このようにSystem.outを操作することには注意してください。 –

答えて

43

Javaはクロスプラットフォームであり、 '/ dev/null'はUnix固有のものです(Windowsには別の方法がありますが、コメントを読んでください)。したがって、出力を無効にするカスタムOutputStreamを作成することをお勧めします。

try { 
    System.out.println("this should go to stdout"); 

    PrintStream original = System.out; 
    System.setOut(new PrintStream(new OutputStream() { 
       public void write(int b) { 
        //DO NOTHING 
       } 
      })); 
    System.out.println("this should go to /dev/null, but it doesn't because it's not supported on other platforms"); 

    System.setOut(original); 
    System.out.println("this should go to stdout"); 
} 
catch (Exception e) { 
    e.printStackTrace(); 
} 
+3

NULデバイスの代わりに、ウィンドウに表示されます。 IIRCは "ファイル名"として "NUL:"です。 –

+0

ああ、これは本当に初めて私はそれについて聞いている!投稿を編集するつもりです。ありがとうございました! –

+3

しかし、これはプラットフォームに依存しない正しい答えですから+1してください。しかし、効率を上げるためにwrite(byte []、int、int)もオーバーライドします。 –

15

あなたは、以下のようにクラスNullPrintStreamを使用することができます。

PrintStream original = System.out; 
System.setOut(new NullPrintStream()); 
System.out.println("Message not shown."); 
System.setOut(original); 

とクラスNullPrintStreamは...

import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.OutputStream; 
import java.io.PrintStream; 

public class NullPrintStream extends PrintStream { 

    public NullPrintStream() { 
    super(new NullByteArrayOutputStream()); 
    } 

    private static class NullByteArrayOutputStream extends ByteArrayOutputStream { 

    @Override 
    public void write(int b) { 
     // do nothing 
    } 

    @Override 
    public void write(byte[] b, int off, int len) { 
     // do nothing 
    } 

    @Override 
    public void writeTo(OutputStream out) throws IOException { 
     // do nothing 
    } 

    } 

} 
+0

NullPrintStreamはどこで入手できますか?どのライブラリですか?または自分でクラスを作成する必要がありますか? –

+0

私のコードにはこれが本当に必要でした...間違いなく、stdoutをサイレンシングするための人生節約者です。 –

2

古い質問ですが、私は知っているが、この小さな行はどうなりますWindows上のトリックですか?

System.setOut(new PrintStream(new File("NUL")));

はるかに少ないコードとは、私にはかなり直接的に見えます。

-3

私は思うSystem.setOut(null);うまくいくはずです。少なくともそれは私のために働いた。

+1

その後System.out.anythingを呼び出すと、NullPointerExceptionがスローされます。それがあなたのために働いていれば、あなたはどこかで例外を捕まえる必要があります。 –

関連する問題