3
3
import java .io .File ;
4
4
import java .io .FileOutputStream ;
5
5
import java .io .IOException ;
6
+ import java .util .Random ;
6
7
7
8
/**
8
9
* Created by bailong on 14/10/11.
@@ -11,6 +12,8 @@ public final class TempFile {
11
12
private TempFile () {
12
13
}
13
14
15
+ static final Random r = new Random ();
16
+
14
17
public static void remove (File f ) {
15
18
f .delete ();
16
19
}
@@ -22,7 +25,62 @@ public static File createFile(int kiloSize) throws IOException {
22
25
File f = File .createTempFile ("qiniu_" + kiloSize + "k" , "tmp" );
23
26
f .createNewFile ();
24
27
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 ();
26
84
long s = 0 ;
27
85
while (s < size ) {
28
86
int l = (int ) Math .min (b .length , size - s );
@@ -42,7 +100,7 @@ public static File createFile(int kiloSize) throws IOException {
42
100
}
43
101
}
44
102
45
- private static byte [] getByte () {
103
+ private static byte [] getByteOld () {
46
104
byte [] b = new byte [1024 * 4 ];
47
105
b [0 ] = 'A' ;
48
106
for (int i = 1 ; i < 1024 * 4 ; i ++) {
0 commit comments