重构来自System的输出.转到PrintStream



如何改变我用来检查结果的System.out
我需要测试这个方法。当输出为PrintStream时,最好这样做。
如何解决这个问题?

代码:

private void scan(File file) {
        Scanner scanner = null;
        int matches = 0;
        try {
            scanner = new Scanner(file);
        } catch (FileNotFoundException e) {
            System.out.println("File Not Found.");
            e.printStackTrace();
        }
        while (scanner.hasNext())
            if (scanner.next().equals(whatFind)) {
                matches++;
            }
        if (matches > 0) {
            String myStr = String.format(
                    "File: %s - and the number of matches " + "is: %d",
                    file.getAbsolutePath(), matches);
            System.out.println(myStr);
        }
    }

问题:

  • 如何重构输出System.outPrintStream

尝试使用
PrintWriter out = new PrintWriter(System.out);

最后不要忘记关闭它。
out.close();

注:out println()System.out.println()

import java.io.PrintStream;
import java.io.PrintWriter;
public class TimeChecker 
{
    public static void main(String[] args) 
    {
        /**
         * Normal System.out.println
         */
        long start = System.currentTimeMillis();
        for(int i=1; i<1000000000; i++);
        long end = System.currentTimeMillis();
        System.out.println((end-start));
        /**
         * Using PrintWriter
         * 
         * Note: The output is displayed only when you write "out.close()"
         * Till then it's in buffer. So once you write close() 
         * then output is printed
         */
        PrintWriter out = new PrintWriter(System.out);
        start = System.currentTimeMillis();
        for(int i=1; i<1000000000; i++);
        end = System.currentTimeMillis();
        out.println((end-start));
        /**
         * Using PrintStream
         */
        PrintStream ps = new PrintStream(System.out, true);
        System.setOut(ps);
        start = System.currentTimeMillis();
        for(int i=1; i<1000000000; i++);
        end = System.currentTimeMillis();
        ps.println((end-start));
        // You need to close this for PrintWriter to display result
        out.close();
    }
}

这会让你了解它们是如何工作的,以及它们之间的区别。
希望这对你有帮助!

尝试如下:PrintStream匿名对象,该对象不会保证关闭流。但是printwwriter保证。

new PrintStream(System.out).print(str);    

这个答案是我从PrintStream编程中得到的。

最新更新