java語言自主程式設計模擬資料檔案
資料格式樣本為:
2018-08-242 19:08:320,15219835179,重慶,小米,http://www.jd.com.htm
在本資料中包含:
時間;
電話;
地點;
手機品牌;
網址;
(1)首先實現輸出時間:
在java中用Date方法可以輸出當前時間
Date date=new Date();
System.out.println(date);
Fri Aug 31 09:01:43 CST 2018
但在資料中時間格式為2018-08-242 19:08:320 所以我們要更改時間的輸出格式
這需要使用SimpleDateFormat 類的format方法
SimpleDateFormat sdf=new SimpleDateFormat(“YYYY-MM-DD HH:MM:SS”)
“YYYY-MM-DD HH:MM:SS”是對Fri Aug 31 09:01:43 CST 2018設定的新格式
即2018-08-242 19:08:320型別;
程式碼為
sdf.format(new date(System.currentTimeMillis()))
System.currentTimeMillis()是當前時間;
由於我們要頻繁的對儲存檔案進行增減的操作故我們將字串儲存於StringBuffer類中,
所以要建立一個StringBuffer類的例項
StringBuffer sb=new StringBuffer();
現在就要對例項sb新增字串;而StringBuffer類中新增字串的方法append()
基於前面的格式,我們還要定義幾個陣列,分別儲存地點citys,手機品牌phone,電話call,網址web等資料;
String[] call= {“136”,”138”,”156”,”188”,”152”,”139”};
String[] citys= {“哈爾濱”,”北京”,”北京”,”上海”,”廣州”,”深圳”,”重慶”,”長春”,”瀋陽”,”大連”};
String[] phone= {“蘋果”,”華為”,”vivo”,”小米”,”蘋果”,”華為”,”oppo”,”三星”,”小米”,”nokia”};
String[] web= {“
為了凸顯資料的隨機性,我們要使用Random類(要導util包);
Random r=new Random();
在準備工作完成後我們就要建立一個新的txt檔案
PrintWriter out=new PrintWriter(“e://log.txt”);
接下來就是向sb中新增資料;
因為我們所模擬的資料檔案很大;且每行資料格式一樣所以我們採用for迴圈;
for(int i=0;i<10000;i++){
StringBuffer sb=new StringBuffer();
sb.append(sdf.format(new Date(System.currentTimeMillis()))).append(“,”);
sb.append(call[r.nextInt(call.length)]);
//內迴圈是為了新增手機號碼的後八位
for(int j=0;j<8;j++) {
sb.append(r.nextInt(10));
}
sb.append(“,”);
sb.append(citys[r.nextInt(citys.length)]).append(“,”);
sb.append(phone[r.nextInt(phone.length)]).append(“,”);
sb.append(web[r.nextInt(web.length)]).append(“.htm”);
out.println(sb);
}
//由於前面使用了PrintWriter 所以在程式執行完後我們要關閉流
out.close();
為方便讀者深入瞭解程式碼結構;完整程式碼若下
package practice0828;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
public class Test1 {
public static void main(String[] args) throws Exception {
Random r=new Random();
String[] call= {“136”,”138”,”156”,”188”,”152”,”139”};
String[] citys= {“哈爾濱”,”北京”,”北京”,”上海”,”廣州”,”深圳”,”重慶”,”長春”,”瀋陽”,”大連”};
String[] phone= {“蘋果”,”華為”,”vivo”,”小米”,”蘋果”,”華為”,”oppo”,”三星”,”小米”,”nokia”};
String[] web= {“http://www.taobao.com“,”http://www.jd.com“,”http://www.vip.com“};
PrintWriter out=new PrintWriter(“e://log.txt”);
SimpleDateFormat sdf=new SimpleDateFormat(“YYYY-MM-DD HH:MM:SS”);
for(int i=0;i<100;i++) {
StringBuffer sb=new StringBuffer();
sb.append(sdf.format(new Date(System.currentTimeMillis()))).append(“,”);
sb.append(call[r.nextInt(call.length)]);
for(int j=0;j<8;j++) {
sb.append(r.nextInt(10));
}
sb.append(“,”);
sb.append(citys[r.nextInt(citys.length)]).append(“,”);
sb.append(phone[r.nextInt(phone.length)]).append(“,”);
sb.append(web[r.nextInt(web.length)]).append(“.htm”);
out.println(sb);
}
out.close();
}
}