2016-12-15 40 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); 
      } 
     } 
    } 
} 

這應該工作,任何問題或意見,隨時問。