如何存储Java循环输出?



这是我的随机邮件生成器代码,我想保存随机邮件,我该怎么做?

public class stupit {
public static void main(String[] args) {
Random randomGenerator = new Random();
for (int i=1; i<=5; i++) {
int randomInt = randomGenerator.nextInt(1000);
System.out.println("username"+randomInt+"@gmail.com");
}
}
}

输出为:

username394@gmail.com
username429@gmail.com
username70@gmail.com
username419@gmail.com
username744@gmail.com

如何保存这些输出像= username394@gmail.cob=username429@gmail.com.....

您需要为要保存这些电子邮件的数据库提供额外的驱动程序库。
您可以在 maven Central 中找到数据库的 jdbc 驱动程序。

对于 mysql 数据库,通用代码可能如下所示:

ArrayList<String> objectsToStore = new ArrayList<>();
Random rnd = new Random();
for (int i = 1; i <= 5; i++) {
objectsToStore.add("username" + rnd.nextInt() + "@gmail.com");
}
try {
//1) this used to load mysql jdbc driver into memory
Class.forName("com.mysql.jdbc.Driver");
//2) create connection to running mysql instance
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName?useSSL=false", "username", "password");
connection.setAutoCommit(false);
Statement statement = connection.createStatement();
for (String x : objectsToStore) {
// this insert will work assuming you have table user_data with email field
statement.executeUpdate("INSERT INTO USER_DATA (email) VALUES ('" + x +"')");
}
//commit transaction
connection.commit();
statement.close();
connection.close();
} catch (Exception e) {
throw new RuntimeException(e);
}

用于在数据库中创建表的 SQL:

create table User_data(
email varchar(255)
);

如果你想保存它们...thn 在循环外声明一个字符串[ ] arrsy....然后尝试使用嵌套循环将邮件地址存储在字符串中...

你也可以使用FileIlnputStrem类将它们存储在文本文件中。在 txt 文件中...