-1

How able to change System.out which I use to check the result.
I need test this method. Better do this when output will be with PrintStream.
How able to solve this?

Code:

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);
        }
    }

Question:

  • How to refactor output System.out to PrintStream?
4

2 に答える 2

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();
    }

}

これにより、それらがどのように機能し、互いに異なるかがわかります。
お役に立てれば!!

于 2013-03-04T12:01:07.343 に答える
0

次のように試してください: ストリームを閉じることを保証しない PrintStream 匿名オブジェクト。しかし、PrintWriter は保証します。

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

PrintStream プログラミングから得たこの回答。

于 2013-03-04T12:16:23.120 に答える