第一个 Java 程序(将排列写入文件)
我正在尝试将重复的组合写入文本文件,问题是我试图在不了解 java 内部工作原理的情况下将一些代码组合在一起。当我重新排列代码时,我不太确定会产生什么影响。
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(input.charAt(i));
brute(input, depth - 1, output);
output.deleteCharAt(output.length() - 1);
}
}
}
}
}
任何帮助表示赞赏
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(input.charAt(i));
brute(input, depth - 1, output);
output.deleteCharAt(output.length() - 1);
}
}
}
}
}
Any help is appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想问题是你在运行应用程序结束时得到一个空文件?
您应该简化写出代码的部分:
每次打开一个文件并将其写出。没关系(最好将其写入已打开的流),但您不需要创建 BufferedWriter ,并且可以进一步简化代码。
如果运行此代码,您仍然会发现它不起作用,它只是在磁盘上生成一个空文件。使用后关闭它很重要。将上面的内容更改为:
似乎使程序可以工作(代码中存在一些语法错误,例如忘记捕获/抛出已检查的异常,但我认为这只是因为代码是手动复制的)。
有关如何进一步整理此问题的建议:
finally
确保文件始终关闭,即使在发生以下情况时也是如此:一个例外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:
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.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:
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:
finally
to ensure that your files are always closed, even in the event of an exception