Linux
dd 命令:
dd if=/dev/zero of=<fileName> bs=<一次復制的大小> count=<復制的次數>
生成 50 MB 的空文件:
dd if=/dev/zero of=50M-1.txt bs=1M count=50
Windows
fsutil 命令:
fsutil file createnew <fileName> <文件大小單位字節>
生成 10MB 的空文件:
fsutil file createnew 10M-1.txt 10485760
Java
用 FileChannel 的 write 方法:
在指定位置插入一個空字符,這個指定的位置下標即生成目標文件的大小,單位為字節
private static void createFixLengthFile(File file, long length) throws IOException { FileOutputStream fos = null; FileChannel outC = null; try { fos = new FileOutputStream(file); outC = fos.getChannel(); // 從給定的文件位置開始,將字節序列從給定緩沖區寫入此通道 // ByteBuffer.allocate 分配一個新的字節緩沖區 outC.write(ByteBuffer.allocate(1), length - 1); } finally { try { if (outC != null) { outC.close(); } if (fos != null) { fos.close(); } } catch (IOException e1) { e1.printStackTrace(); } } }
第二種,用 RandomAccessFile 的 setLength 方法更為方便:
private static void createFile(File file, long length) throws IOException { RandomAccessFile r = null; try { r = new RandomAccessFile(file, "rw"); r.setLength(length); } finally { if (r != null) { r.close(); } } }