2016-12-15 101 views
0

有没有办法为变量N的每个不同值创建10个随机文件。我想在空间100,50000之间有五个N值。值之间的差异应至少为5000.因此,对于N的每个值,我想要创建10个不同的文件并向它们写入随机值。例如,文件格式可以是这样的:创建随机内容文件

0 2 
5 12 
8 23 
10 53 
56 98 
... 
+0

到目前为止,我还没有任何想法。 –

+1

至少写入伪代码。事情是,我们不想为你写一个完整的程序,特别是不知道你的问题是什么 - 你有写入文件的问题吗?你生成随机数有问题吗?你使用搜索引擎发现了什么,为什么你不能应用它? – Aziuth

+0

您可以先检查在java中创建文件的文档,然后再查看如何生成随机字符串。不要为某人做你的工作。 – Gatusko

回答

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()

祝你好运。

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); 
      } 
     } 
    } 
} 

这应该工作,任何问题或意见,随时问。