我的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);
}
}
}
frameworkcucc:
package hu.hymosi.tut;
import java.io.PrintWriter;
public class frameworkcucc {
public void writetotext(int write, PrintWriter writer) {
writer.print(write + "\n");
}
}
如果我运行该程序,它只会在我的txt文件中写入一行。 什么是错误,我该如何解决?
答案 0 :(得分: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()
答案 1 :(得分:0)
您需要flush
PrintWriter
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");
}
}
一次,并在循环之前检查空值这是一些略微改进的代码(请注意包等已更改)。
{{1}}