生成NGB的数据文件的方法,N是自然数,对应不同的文件大小。
1.生成文件的方法
private static void writeFile(int N) {
if (N < 1) {
System.out.println("writeFile please input one integer greater than 0");
return;
}
System.out.println("writeFile start >>>");
RandomAccessFile file = null;
try {
System.out.println("Will write " + N + "GB data ...");
final String FILE_NAME = N + "GB.bin";
File f = new File(FILE_NAME);
if (f.exists()) {
f.delete();
}
file = new RandomAccessFile(FILE_NAME, "rw");
final int ONE_G_LENGTH = 1073741824; // 1G
byte[] b = new byte[ONE_G_LENGTH]; // 1 GB
b[0] = '0';
b[b.length - 1] = '1';
for (int i = 0; i < N; ++i) {
file.write(b);
file.seek(file.length());
System.out.println("write " + (i + 1) + "GB data");
}
file.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
file = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("writeFile end <<<");
}
2.调用方法
由于生成大文件耗时较长,所以放在新线程中调用。
(1)例如生成1GB的文件:
new Thread(new Runnable() {
@Override
public void run() {
writeFile(1);
}
}).start();
(2)log输出:
writeFile start >>>
Will write 1GB data ...
write 1GB data
writeFile end <<<
(3)在源码根目录下生成的大文件: