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.
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. 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. Just be sure to close the variable in a finally block in your main method after calling your recursive method.
精彩评论