import java.io.*;
import java.util.Random;
public class LargeDataset {
public static void main(String[] args) throws Exception {
File file = new File("src/Salary.txt");
if (file.exists()) {
System.out.print("Sorry this file already exists.");
System.exit(0);
}
String firstName = "";
String lastName = "";
String rank = "";
double salaryRange = 0.0;
for (int i = 1; i <= 1000; i++) {
try (PrintWriter output = new PrintWriter(file))
{
firstName = "FirstName" + i;
lastName = "LastName" + i;
rank = generateRandomRank();
if (rank == "assistant")
salaryRange = generateSalary(50000.00, 80000.00);
else if (rank == "associate")
salaryRange = generateSalary(60000.00, 110000.00);
else
salaryRange = generateSalary(75000.00, 130000.00);
output.printf("%s %s %s $%.2f", firstName, lastName, rank, salaryRange);
output.println();
}
}
}
public static String generateRandomRank() {
String[] rank = {"assistant", "associate", "full"};
Random random1 = new Random();
return rank[random1.nextInt(3)];
}
public static double generateSalary(double minSalary, double maxSalary) {
double randomSalary = minSalary + Math.random() * (maxSalary - minSalary);
return randomSalary;
}
}
大家好。我有一个生成1000行文本的程序,并将其保存到名为Salary的文件中。每行的格式为:firstNamei,lastNamei,随机排名和适合排名的随机薪水。但是当我运行这个程序时,它只输出循环的第1000行。但是我注意到,当我没有将PrintWriter放在try语句中并在循环后自行关闭它时,它运行正常并生成所有1000行。为什么它只根据现在的情况生成最后一行呢?
答案 0 :(得分:0)
您应该打开PrintWriter
一次,然后从循环中多次写入,而不是相反:
try (PrintWriter output = new PrintWriter(file)) {
for (int i = 1; i <= 1000; i++) {
firstName = "FirstName" + i;
lastName = "LastName" + i;
rank = generateRandomRank();
if (rank == "assistant")
salaryRange = generateSalary(50000.00, 80000.00);
else if (rank == "associate")
salaryRange = generateSalary(60000.00, 110000.00);
else
salaryRange = generateSalary(75000.00, 130000.00);
output.printf("%s %s %s $%.2f", firstName, lastName, rank, salaryRange);
output.println();
}
}
您应该使用上述模式而不是您拥有的模式。如果您想要对当前代码进行精确修复,那么您可以尝试在追加模式下打开PrintWriter
:
for (int i=1; i <= 1000; i++) {
try (PrintWriter output = new PrintWriter(new FileOutputStream(file, true)) {
// same logic
}
}
这也应该有效,因为现在,即使你为循环的每次迭代创建一个新的PrintWriter
(效率低下),你也可以在追加模式下打开底层文件,所以每个新行应该写得正确。
答案 1 :(得分:0)
每次迭代1000
时,您都在创建新文件
for (int i = 1; i <= 1000; i++) {
try (PrintWriter output = new PrintWriter(file))
...
}
在循环之前移动它
try (PrintWriter output = new PrintWriter(file)) {
for (int i = 1; i <= 1000; i++) {
}
}