简体   繁体   English

在哪里放置PrintStream对象以打印变量java

[英]Where to put a PrintStream object to print a variable java

I have a code that generates combinations and prints to screen, I'd like to print this to a file but Im not sure where to put my PrintStream object to have access to the String I'd like to print. 我有一个生成组合并打印到屏幕的代码,我想将此打印到文件中,但是我不确定将PrintStream对象放在哪里可以访问我想打印的字符串。

public class Main {
public static void main(String args[]) {
    brute("12345", 5, new StringBuffer());
}
static void brute(String input, int depth, StringBuffer output) {
    if (depth == 0) {
        System.out.println(output);
    } else {
        for (int i = 0; i < input.length(); i++) {
            output.append(input.charAt(i));
            brute(input, depth - 1, output);
            output.deleteCharAt(output.length() - 1); 
            }
        }   
    }
}

Thanks, 谢谢,

Just add PrintStream as one of the parameters for your brute() method and pass it along for the recursive call. 只需将PrintStream添加为brute()方法的参数之一,并将其​​传递给递归调用即可。 Then in your main you just need: 然后在您的主体中,您只需要:

FileOutputStream fileOut = new FileOutputStream("output.txt");
brute("12345", 5, new StringBuffer(), new PrintStream(fileOut));

One way is to have a Static PrintWriter variable that your method writes to rather than the System.out. 一种方法是让方法写入的是静态PrintWriter变量,而不是System.out。 Just be sure to close the variable in a finally block in your main method after calling your recursive method. 只需确保在调用递归方法后在main方法的finally块中关闭变量即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM