将System.out的输出重构为PrintStream

时间:2013-03-04 11:58:32

标签: java refactoring

如何更改我用来检查结果的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.out重构为PrintStream

2 个答案:

答案 0 :(得分:1)

尝试使用此 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();
    }

}

这将让您了解它们的工作原理和彼此之间的差异 希望这会有所帮助!!

答案 1 :(得分:0)

尝试这样:PrintStream匿名对象,不保证关闭流。但PrintWriter保证。

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

我从PrintStream programming得到了这个答案。