I'm trying to write combinations with repetitions to a text file, the problems is I'm trying to hack together some code without knowing the inner workings of java. I'm not really sure what I'm effecting when I'm rearranging the code.
import java.io.*;
public class Main {
public static void main(String args[]) {
brute("123", 3, new StringBuffer());
}
static void brute(String input, int depth, StringBuffer output) {
if (depth == 0) {
// System.out.println(output);
{
try{
// Create file
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("blah" + output);}
else {
for (int i = 0; i < input.length(); i++) {
output.append开发者_JS百科(input.charAt(i));
brute(input, depth - 1, output);
output.deleteCharAt(output.length() - 1);
}
}
}
}
}
Any help is appreciated
I guess the problem is that you get an empty file at the end of running the application?
You should simplify the bit that writes the code out:
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("blah" + output);
You're opening a file each time and writing it out. That's ok (best to write it to an already opened stream), but you don't need to create a BufferedWriter
and you can simplify the code a bit more.
FileWriter fstream = new FileWriter("out.txt", true);
fstream.append(output);
If you run this code you'll still find that it doesn't work and it just produces an empty file on disk. It's important to close the after you've used it. Changing the above to:
FileWriter fstream = new FileWriter("out.txt", true);
fstream.append(output).append('\n');
fstream.close();
Seems to make the program work (there's a few syntax errors in the code, such as forgetting to catch/throw the checked exceptions, but I assume that's just because the code was copied in manually).
Suggestions for how to tidy this up more:
- Write to a stream instead of opening and closing the file every time you write an item out
- Use
finally
to ensure that your files are always closed, even in the event of an exception
精彩评论