英文:
Java - Nested For loop - Better way to append to File for every System.out.println
问题
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
class GenerateTestData {
public static void main(String[] args) throws IOException {
File outfile = new File("dbscript_output.sql");
if (outfile.exists()) {
outfile.delete();
}
int totalCluster = 2;
int totalAgency = totalCluster * 10;
int totalProgramArea = totalAgency * 20;
int totalUsers = totalProgramArea * 100;
for (int numCluster = 1; numCluster <= totalCluster; ++numCluster) {
System.out.println("\nCluster__________________________" + numCluster);
writeToFile("\nCluster__________________________" + numCluster);
for (int numAgency = 1; numAgency <= totalAgency; ++numAgency) {
System.out.println("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
writeToFile("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
for (int numProgramArea = 1; numProgramArea <= totalProgramArea; ++numProgramArea) {
System.out.println("\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
writeToFile("\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
for (int numUser = 1; numUser <= totalUsers; ++numUser) {
System.out.println("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
writeToFile("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
}
}
}
}
}
private static void writeToFile(String data) throws IOException {
File file = new File("dbscript_output.sql");
FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr);
br.write(data);
br.close();
fr.close();
}
}
Question: 有没有更好的方法来实现这个?Java 7/8/11 有没有更好的API来做这个?我愿意尝试使用任何更短/更智能的方法来使用Java。这里展示的示例只是一小部分。我有16个实体需要准备测试数据,它们之间都有连接(关联)。谢谢。
UPDATE:
请允许我重新提问。
有没有任何更短/更智能的方法来使用纯粹的Java核心1.8+来实现上述内容?我是否可以将(合并)'for'循环和'writeToFile'合并在一起?(也许是一行代码?)非常感谢大家的帮助。
英文:
I am using the below code to generate some Test Data which gets the job done. No problems here.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
class GenerateTestData {
public static void main(String[] args) throws IOException {
File outfile = new File("dbscript_output.sql");
if (outfile.exists()) {
outfile.delete();
}
int totalCluster = 2;
int totalAgency = totalCluster * 10;
int totalProgramArea = totalAgency * 20;
int totalUsers = totalProgramArea * 100;
for (int numCluster = 1; numCluster <= totalCluster; ++numCluster) {
System.out.println("\nCluster__________________________" + numCluster);
writeToFile("Cluster__________________________" + numCluster);
for (int numAgency = 1; numAgency <= totalAgency; ++numAgency) {
System.out.println("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
writeToFile("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
for (int numProgramArea = 1; numProgramArea <= totalProgramArea; ++numProgramArea) {
System.out.println("\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
writeToFile("\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
for (int numUser = 1; numUser <= totalUsers; ++numUser) {
System.out.println("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
writeToFile("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
}
}
}
}
}
private static void writeToFile(String data) throws IOException {
File file = new File("dbscript_output.sql");
FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr);
br.write(data);
br.close();
fr.close();
}
}
Question: Is there a better way to achieve it? Does Java 7/8/11 has any better API to do it? I am open for any shorter/smarter way of doing it using Java. The sample shown here is just a few elements. I have 16 Entities for which I have to prepare Test Data and all of them are connected (related). Thanks.
UPDATE
Please allow me to reframe the question.
Is there any shorter/smarter way to achieve above using pure Core Java 1.8+ ? Where I can club (merge) 'for' loop and 'writeToFile'? (in one liner may be?) Appreciate all for your help.
答案1
得分: 1
以下是翻译好的部分:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
class GenerateTestData {
public static void main(String[] args) throws IOException {
int totalCluster = 2;
int totalAgency = totalCluster * 10;
int totalProgramArea = totalAgency * 20;
int totalUsers = totalProgramArea * 100;
// 使用 try-with-resources 语句
try (BufferedWriter br = new BufferedWriter(new FileWriter("dbscript_output.sql"))) {
for (int numCluster = 1; numCluster <= totalCluster; ++numCluster) {
writeOutput(br, "Cluster__________________________" + numCluster);
for (int numAgency = 1; numAgency <= totalAgency; ++numAgency) {
writeOutput(br, "\n\tCluster_" + numCluster + "_Agency_" + numAgency);
for (int numProgramArea = 1; numProgramArea <= totalProgramArea; ++numProgramArea) {
writeOutput(br, "\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
for (int numUser = 1; numUser <= totalUsers; ++numUser) {
writeOutput(br, "\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
}
}
}
}
}
}
private static void writeOutput(BufferedWriter br, String data) throws IOException {
System.out.println(data);
br.write(data);
}
}
英文:
It's better to only open the file once (as opposed to opening and closing it for each entry).
Also, you can use the try-with-resources statement to ensure that the output file is closed automatically.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
class GenerateTestData {
public static void main(String[] args) throws IOException {
int totalCluster = 2;
int totalAgency = totalCluster * 10;
int totalProgramArea = totalAgency * 20;
int totalUsers = totalProgramArea * 100;
// try-with-resources statement
try (BufferedWriter br = new BufferedWriter(new FileWriter("dbscript_output.sql"))) {
for (int numCluster = 1; numCluster <= totalCluster; ++numCluster) {
writeOutput(br, "Cluster__________________________" + numCluster);
for (int numAgency = 1; numAgency <= totalAgency; ++numAgency) {
writeOutput(br,"\n\tCluster_" + numCluster + "_Agency_" + numAgency);
for (int numProgramArea = 1; numProgramArea <= totalProgramArea; ++numProgramArea) {
writeOutput(br,"\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
for (int numUser = 1; numUser <= totalUsers; ++numUser) {
writeOutput(br,"\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
}
}
}
}
}
}
private static void writeOutput(BufferedWriter br, String data) throws IOException {
System.out.println(data);
br.write(data);
}
}
答案2
得分: 1
如我们的同事在上面提到的,您可以按如下方式使用try with resources(这样您就不必关闭每个输入流)。您还可以使用流来简化/改变嵌套的for循环,但这并不是一个更清晰的解决方案,您需要改进它。
public class GenerateTestData {
public static void main(String[] args) throws IOException {
File outfile = new File("dbscript_output2.sql");
if (outfile.exists()) {
outfile.delete();
}
int totalCluster = 2;
int totalAgency = totalCluster * 10;
int totalProgramArea = totalAgency * 20;
int totalUsers = totalProgramArea * 100;
IntStream.range(0, totalCluster).forEach(numCluster -> {
writeToFile("Cluster__________________________" + numCluster);
IntStream.range(0, totalAgency).forEach(numAgency -> {
writeToFile("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
IntStream.range(0, totalProgramArea).forEach(numProgramArea ->
IntStream.range(0, totalUsers).forEach(numUser -> {
writeToFile("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
}));
});
});
}
private static void writeToFile(String data) {
File file = new File("dbscript_output2.sql");
try (FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr)) {
br.write(data);
System.out.println(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
英文:
As our colleague mentioned above you can use try with resources as below (so you dont have to close every input stream). You can also short/change nested for loops with streams but it isn't clearer solution and you have to improve it.
public class GenerateTestData {
public static void main(String[] args) throws IOException {
File outfile = new File("dbscript_output2.sql");
if (outfile.exists()) {
outfile.delete();
}
int totalCluster = 2;
int totalAgency = totalCluster * 10;
int totalProgramArea = totalAgency * 20;
int totalUsers = totalProgramArea * 100;
IntStream.range(0, totalCluster).forEach(numCluster->{
writeToFile("Cluster__________________________" + numCluster);
IntStream.range(0, totalAgency).forEach(numAgency->{
writeToFile("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
IntStream.range(0, totalProgramArea).forEach(numProgramArea->
IntStream.range(0,totalUsers).forEach(numUser->{
writeToFile("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea
+ "_User_" + numUser);
}));
});
});
}
private static void writeToFile(String data) {
File file = new File("dbscript_output2.sql");
try(FileWriter fr = new FileWriter(file, true);
BufferedWriter br = new BufferedWriter(fr)) {
br.write(data);
System.out.println(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案3
得分: 1
在下面的替代方案中,嵌套循环已被重构为单独的方法,文件仅被打开一次,并在使用完毕后关闭。虽然代码行数没有减少,但可能更易读一些。无论如何,希望这能给您一些灵感。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.function.Consumer;
import java.util.stream.IntStream;
class GenerateTestData {
static int TOTAL_CLUSTER = 2;
static int TOTAL_AGENCY = TOTAL_CLUSTER * 2;
static int TOTAL_PROGRAM_AREA = TOTAL_AGENCY * 2;
static int TOTAL_USERS = TOTAL_PROGRAM_AREA * 2;
public static void main(String[] args) throws IOException {
File outfile = new File("dbscript_output2.sql");
if (outfile.exists()) {
outfile.delete();
}
try (BufferedWriter br = new BufferedWriter(new FileWriter(outfile, true))) {
createClusters(str -> writeLine(br, str));
}
}
private static void writeLine(BufferedWriter writer, String data) {
try {
System.out.println(data);
writer.write(data);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void createClusters(Consumer<String> consumer) {
IntStream.range(1, TOTAL_CLUSTER).forEach(numCluster -> {
consumer.accept("Cluster__________________________" + numCluster);
createAgencies(consumer, numCluster);
});
}
private static void createAgencies(Consumer<String> consumer, int numCluster) {
IntStream.range(1, TOTAL_AGENCY).forEach(numAgency -> {
consumer.accept("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
createProgramAreas(consumer, numAgency);
});
}
private static void createProgramAreas(Consumer<String> consumer, int numAgency) {
IntStream.range(1, TOTAL_PROGRAM_AREA).forEach(numProgramArea -> {
consumer.accept("\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
createUsers(consumer, numAgency, numProgramArea);
});
}
private static void createUsers(Consumer<String> consumer, int numAgency, int numProgramArea) {
IntStream.range(1, TOTAL_USERS).forEach(numUser -> {
consumer.accept("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea + "_User_" + numUser);
});
}
}
英文:
In the alternative below the nested loops have been refactored into separate methods and the file is opened just once and closed once you're done with it. It's not shorter but perhaps a bit more readable. Anyway, hope this gives you some inspiration.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.function.Consumer;
import java.util.stream.IntStream;
class GenerateTestData {
static int TOTAL_CLUSTER = 2;
static int TOTAL_AGENCY = TOTAL_CLUSTER * 2;
static int TOTAL_PROGRAM_AREA = TOTAL_AGENCY * 2;
static int TOTAL_USERS = TOTAL_PROGRAM_AREA * 2;
public static void main(String[] args) throws IOException {
File outfile = new File("dbscript_output2.sql");
if (outfile.exists()) {
outfile.delete();
}
try (BufferedWriter br = new BufferedWriter(new FileWriter(outfile, true))) {
createClusters(str -> writeLine(br, str));
}
}
private static void writeLine(BufferedWriter writer, String data) {
try {
System.out.println(data);
writer.write(data);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void createClusters(Consumer<String> consumer) {
IntStream.range(1, TOTAL_CLUSTER).forEach(numCluster -> {
consumer.accept("Cluster__________________________" + numCluster);
createAgencies(consumer, numCluster);
});
}
private static void createAgencies(Consumer<String> consumer, int numCluster) {
IntStream.range(1, TOTAL_AGENCY).forEach(numAgency -> {
consumer.accept("\n\tCluster_" + numCluster + "_Agency_" + numAgency);
createProgramAreas(consumer, numAgency);
});
}
private static void createProgramAreas(Consumer<String> consumer, int numAgency) {
IntStream.range(1, TOTAL_PROGRAM_AREA).forEach(numProgramArea -> {
consumer.accept("\n\t\tAgency_" + numAgency + "_ProgramArea_" + numProgramArea);
createUsers(consumer, numAgency, numProgramArea);
});
}
private static void createUsers(Consumer<String> consumer, int numAgency, int numProgramArea) {
IntStream.range(1, TOTAL_USERS).forEach(numUser -> {
consumer.accept("\n\t\t\tAgency_" + numAgency + "_" + "ProgramArea_" + numProgramArea + "_User_" + numUser);
});
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论