Java、Linux、Win 快速產生指定大小的空檔案

來源:互聯網
上載者:User

標籤:puts   stat   throws   span   utc   nal   random   位元組序   throw   

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 方法:

在指定位置插入一個Null 字元,這個指定的位置下標即產生目標檔案的大小,單位為位元組

    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();            }        }   }
參考資料:

http://jk-t.iteye.com/blog/1930414

Java、Linux、Win 快速產生指定大小的空檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.