-2

我的 java 程序只向 txt 文件写入一行。

代码:主要:

package hu.hymosi.tut;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Random;

public class Main {

public static void main(String[] args) {
    PrintWriter out = null;
    frameworkcucc fw = new frameworkcucc();
    for (int i = 1; i < 100; i++) {
        Random rand = new Random();
        System.out.println(i);

        try {
            out = new PrintWriter("valtozok.txt");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int kiirando = rand.nextInt();

        fw.writetotext(kiirando, out);
    }
}

}

框架cucc:

package hu.hymosi.tut;

import java.io.PrintWriter;

public class frameworkcucc {

public void writetotext(int write, PrintWriter writer) {
    writer.print(write + "\n");
}

}

如果我运行程序,它只会在我的 txt 文件中写入一行。什么是错误,我该如何解决?

4

2 回答 2

3

您正在每次迭代中创建一个新的 PrintWriter。将其移出循环。

try {
            out = new PrintWriter("valtozok.txt");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

 for (int i = 1; i < 100; i++) {
        Random rand = new Random();
        System.out.println(i);
        int kiirando = rand.nextInt();

        fw.writetotext(kiirando, out);
    }
}

清理资源也是一个好习惯,它也会刷新缓冲区:

out.close()
于 2013-09-14T07:30:27.403 回答
0

您需要flushPrintWriter的才能将文本添加到您的文件中。

其他观察:

  • Random在循环外只初始化一次
  • 在循环外只初始化PrintWriter一次并在循环前检查空值

这是一些稍微改进的代码(请注意包等已更改)。

package test;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Random;

public class Main {
    public static void main(String[] args) {
        // initialized before loop
        PrintWriter out = null;
        // proper naming convention
        Frameworkcucc fw = new Frameworkcucc();
        try {
            out = new PrintWriter("valtozok.txt");
        }
        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // initialized before loop
        Random rand = new Random();
        for (int i = 1; i < 100; i++) {

            System.out.println(i);

            int kiirando = rand.nextInt();

            fw.writetotext(kiirando, out);
        }
        // flushing and closing
        out.flush();
        out.close();
    }

}

class Frameworkcucc {

    public void writetotext(int write, PrintWriter writer) {
        writer.print(write + "\n");
    }
}
于 2013-09-14T07:30:58.000 回答