JAVA自定义输出指定大小文件

方法一:使用java 中的FileChannel类,主要用于GB大小等较大文件的创建。

 /**
     * create file in GB size
     * @param length the number of byte in file
     */
    public static void createBigFile(int length){ //1MB文件 length = 1024*1024 = 1048576
        File file =  new File("F:\\testBig.txt");
        FileOutputStream fileOutputStream =null;
        FileChannel fileChannel = null;
        try{
            if(!file.exists()){
                file.createNewFile();
                System.out.println("create");
            }
            fileOutputStream = new FileOutputStream(file);
            fileChannel = fileOutputStream.getChannel();
            fileChannel.write(ByteBuffer.allocate(1),length-1);
            if(fileOutputStream!=null){
                fileOutputStream.close();
            }
            if(fileChannel!=null){
                fileChannel.close();
            }
        } catch (Exception e){
                e.printStackTrace();
        }
    }

方法二:使用RandomAccessFile类,主要用于KB、MB等大小文件的创建。

 /**
     *create file in MB or KB size
     * @param length the byte length of file
     */
    public static byte[] createSmallFile(long length){  //1KB文件 length = 1024
        File file =  new File("F:\\testSmall.txt");
        RandomAccessFile randomAccessFile = null;
        byte[] bytes= null;
        try {
            if(!file.exists()){
                file.createNewFile();
                System.out.println("create new file");
            }
            randomAccessFile = new RandomAccessFile(file,"rw");
            randomAccessFile.setLength(length);
            if(randomAccessFile!=null){
                randomAccessFile.close();
            }
            InputStream in= null;
            in = new FileInputStream(file); //真正要用到的是FileInputStream类的read()方法
            bytes= new byte[in.available()]; //in.available()是得到文件的字节数
            in.read(bytes); //把文件的字节一个一个地填到bytes数组中
            in.close(); //记得要关闭in

        }catch (Exception e){
            e.printStackTrace();
        }
        String s = new String(bytes);
        return bytes;
    }

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值