33import java .io .File ;
44import java .io .FileOutputStream ;
55import java .io .IOException ;
6+ import java .util .Random ;
67
78/**
89 * Created by bailong on 14/10/11.
@@ -11,6 +12,8 @@ public final class TempFile {
1112 private TempFile () {
1213 }
1314
15+ static final Random r = new Random ();
16+
1417 public static void remove (File f ) {
1518 f .delete ();
1619 }
@@ -22,7 +25,62 @@ public static File createFile(int kiloSize) throws IOException {
2225 File f = File .createTempFile ("qiniu_" + kiloSize + "k" , "tmp" );
2326 f .createNewFile ();
2427 fos = new FileOutputStream (f );
25- byte [] b = getByte ();
28+ byte [] b = getByte ((byte ) r .nextInt ());
29+ long s = 0 ;
30+ while (s < size ) {
31+ int l = (int ) Math .min (b .length , size - s );
32+ fos .write (b , 0 , l );
33+ s += l ;
34+ // 随机生成的文件的每一段(<4M)都不一样
35+ b = getByte ((byte ) r .nextInt ());
36+ }
37+ fos .flush ();
38+ return f ;
39+ } finally {
40+ if (fos != null ) {
41+ try {
42+ fos .close ();
43+ } catch (IOException e ) {
44+ e .printStackTrace ();
45+ }
46+ }
47+ }
48+ }
49+
50+ private static byte [] getByte (byte b ) {
51+ int len = 498 * 4 ;
52+ byte [] bs = new byte [len ];
53+
54+ for (int i = 1 ; i < len ; i ++) {
55+ bs [i ] = b ;
56+ }
57+
58+ bs [10 ] = (byte ) r .nextInt ();
59+ bs [9 ] = (byte ) r .nextInt ();
60+ bs [8 ] = (byte ) r .nextInt ();
61+ bs [7 ] = (byte ) r .nextInt ();
62+ bs [6 ] = (byte ) r .nextInt ();
63+ bs [5 ] = (byte ) r .nextInt ();
64+ bs [4 ] = (byte ) r .nextInt ();
65+ bs [3 ] = (byte ) r .nextInt ();
66+ bs [3 ] = (byte ) r .nextInt ();
67+ bs [1 ] = (byte ) r .nextInt ();
68+ bs [0 ] = (byte ) r .nextInt ();
69+
70+ bs [len - 2 ] = '\r' ;
71+ bs [len - 1 ] = '\n' ;
72+ return bs ;
73+ }
74+
75+
76+ public static File createFileOld (int kiloSize ) throws IOException {
77+ FileOutputStream fos = null ;
78+ try {
79+ long size = (long ) (1024 * kiloSize );
80+ File f = File .createTempFile ("qiniu_" + kiloSize + "k" , "tmp" );
81+ f .createNewFile ();
82+ fos = new FileOutputStream (f );
83+ byte [] b = getByteOld ();
2684 long s = 0 ;
2785 while (s < size ) {
2886 int l = (int ) Math .min (b .length , size - s );
@@ -42,7 +100,7 @@ public static File createFile(int kiloSize) throws IOException {
42100 }
43101 }
44102
45- private static byte [] getByte () {
103+ private static byte [] getByteOld () {
46104 byte [] b = new byte [1024 * 4 ];
47105 b [0 ] = 'A' ;
48106 for (int i = 1 ; i < 1024 * 4 ; i ++) {
0 commit comments