java秒建指定大小的文件

java創建指定大小的文件 ,秒建任意大小的文件

package Dirty.File;

import lombok.Cleanup;
import lombok.SneakyThrows;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @ClassName createNeedFile
 * @Descriptiom TODO 創建指定大小的文件
 * @Author KING
 * @Date 2019/3/29 11:56
 * @Version 1.2.1
 **/
public class createNeedFile {


    static final Long length = 100*1024*1024*1024L;


    @SneakyThrows
    public static void main(String[] args) {
        String file  = "D:\\Downloads\\";  //指定創建文件的目錄,文件命名方式爲文件大小
        Long L ;
        String print;
        if ((length>>10)<1){
            L = length;
            print =L + "byte";
            file += print;
        }
        else if((length>>20)<1){
            L = length>>10;
            print = L + "KB";
            file += print;
        }
        else if((length>>30)<1){
            L = length>>20;
            print = L + "MB";
            file += print;
        }
        else if((length>>40)<1){
            L = length>>30;
            print = L + "GB";
            file += print;
        }
        else if((length>>50)<1){
            L = length>>40;
            print = L + "TB";
            file += print;
        }
        else {
            throw new IOException("File too large");
        }
        create(new File(file),length,print);
    }

    @SneakyThrows
    public static void create(File file, long length,String print){
        long start = System.currentTimeMillis();
        @Cleanup RandomAccessFile r = new RandomAccessFile(file, "rw");
        r.setLength(length);
        long end = System.currentTimeMillis();
        System.out.println("create file :" + file);
        System.out.println("file length :" + print);
        System.out.println("run time : " + (end-start) + "ms");
    }
}

main方法裏的一堆是閒着沒事兒玩的,如果各位有時間做一個十分合理的邏輯,本Rookie感激不盡

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章