这里有段代码
1 import java.io.File; 2 import java.io.FileOutputStream; 3 import java.util.Random; 4 5 public class GenerateFile { 6 private String filePath; 7 private long fileSize; 8 public GenerateFile(String filePath, long fileSize) { 9 this.filePath = filePath; 10 this.fileSize = fileSize; 11 } 12 13 public long generate() { 14 int[] number = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 };// 0~9的unicode码 15 File file = new File(filePath); 16 FileOutputStream out = null; 17 byte[] enter = { 10 };// 回车 18 Random r = new Random(); 19 long beginTime = System.currentTimeMillis(); 20 try { 21 out = new FileOutputStream(file); 22 while (file.length() < fileSize) {// 生成n行数字 23 int length = (int) (Math.random() * 8) + 1;/* 长度为0~9 */ 24 boolean sign = (int) (Math.random() * 2) >= 1;// 随机写入正负数 25 26 if (!sign) { 27 out.write(45);// 写入负号 28 } 29 out.write(number[(int) (Math.random() * 9) + 1]);// 第一个不能是0 30 for (int j = 1; j < length; ++j) { 31 out.write(number[(int) (Math.random() * 10)]);/* 生成数字 */ 32 } 33 out.write(enter); 34 } 35 out.close(); 36 } catch (Exception e) { 37 e.printStackTrace(); 38 } 39 long endTime = System.currentTimeMillis(); 40 System.out.println("##########" + (endTime-beginTime) / 1000 + "s"); 41 return endTime - beginTime; 42 } 43 }
1 import java.io.File; 2 import java.io.FileOutputStream; 3 import java.util.Random; 4 5 public class GenerateFile { 6 private String filePath; 7 private long fileSize; 8 public GenerateFile(String filePath, long fileSize) { 9 this.filePath = filePath; 10 this.fileSize = fileSize; 11 } 12 13 public long generate() { 14 int[] number = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 };// 0~9的unicode码 15 File file = new File(filePath); 16 FileOutputStream out = null; 17 byte[] enter = { 10 };// 回车 18 Random r = new Random(); 19 long beginTime = System.currentTimeMillis(); 20 try { 21 out = new FileOutputStream(file); 22 while (file.length() < fileSize) {// 生成n行数字 23 int length = (int) (Math.random() * 8) + 1;/* 长度为0~9 */ 24 out.write(length); 25 out.write(enter); 26 } 27 out.close(); 28 } catch (Exception e) { 29 e.printStackTrace(); 30 } 31 long endTime = System.currentTimeMillis(); 32 System.out.println("##########" + (endTime-beginTime) / 1000 + "s"); 33 return endTime - beginTime; 34 } 35 }
调用:
1 public static void main(String[] args) { 2 GenerateFile gen = new GenerateFile("c:\test\numbers.txt", 1024*1000); 3 4 gen.generate(); 5 }
不知道为什么前面代码的效率比后面代码的效率要高,记录一下