Java 產生隨機數並寫入txt文檔中


源代碼:

import java.io.*;
import java.util.Random;


public class AlgorithmTest 
{    
    public static void main(String[] args)
    {
        String filepath = System.getProperty("user.dir");    
        filepath +="\\data.txt";
        System.out.println(filepath);
        
        try 
        {
            File file = new File(filepath);            
            if(!file.exists())
            {    //如果不存在data.txt文件則創建
                file.createNewFile();
                System.out.println("data.txt創建完成");                
            }
            FileWriter fw = new FileWriter(file);        //創建文件寫入
            BufferedWriter bw = new BufferedWriter(fw);
            
            //產生隨機數據,寫入文件
            Random random = new Random();
            for(int i=0;i<10000;i++)
            {    
                int randint =(int)Math.floor((random.nextDouble()*100000.0));    //產生0-10000之間隨機數        
                bw.write(String.valueOf(randint));        //寫入一個隨機數
                bw.newLine();        //新的一行
            }
            bw.close();
            fw.close();
            
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }        
    }    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM