有没有办法为变量N的每个不同值创建十个随机文件。我希望在空间100,50000之间有五个N值。值之间的差异应该至少为5000.因此,对于N的每个值,我想创建10个不同的文件并为它们写入随机值。例如,文件格式可以是这样的:
0 2
5 12
8 23
10 53
56 98
...
答案 0 :(得分:0)
使用commons.io
写入文件/**
* Méthode permettant de créer un nouveau fichier ou d'écraser un fichier
* existant, tout en lui insérant un contenu.
*
* @param strContenu
* Chaine à insérer dans le fichier texte
* @param strPathFichier
* Chemin du fichier à créer
* @throws IOException
*/
public static String creerFichierPlusContenu( final String strContenu,
final String strPathFichier)
throws IOException {
if (strContenu == null || strPathFichier == null) {
return null;
}
File parentFile = new File(strPathFichier).getParentFile();
if (!parentFile.exists() && !parentFile.mkdirs()) {
return null;
}
FileOutputStream fileOut = new FileOutputStream(strPathFichier);
IOUtils.write(strContenu, fileOut, "UTF-8");
IOUtils.closeQuietly(fileOut);
return strPathFichier;
}
生成随机数:
的Math.random()
祝你好运。答案 1 :(得分:0)
/**
* Code Used: http://stackoverflow.com/questions/30284921/creating-a-text-file-filled-with-random-integers-in-java
* Modified by: Ilya Kuznetsov (12/15/2016)
*/
import java.io.*;
import java.util.*;
public class FillFiles {
public static void main() {
for (int i = 0; i < 10; i++) {
File file = new File("random" + i + ".txt");
FileWriter writesToFile = null;
try {
// Create file writer object
writesToFile = new FileWriter(file);
// Wrap the writer with buffered streams
BufferedWriter writer = new BufferedWriter(writesToFile);
int line;
Random rand = new Random();
for (int j = 0; j < 10; j++) {
// Randomize an integer and write it to the output file
line = rand.nextInt(50000);
writer.write(line + "\n");
}
// Close the stream
writer.close();
}
catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
}
}
这应该有效,任何问题或意见,随时可以提出。