一个生成指定大小文件的东东

这是一个Java程序,用于创建指定大小的文件。通过使用FileOutputStream和FileChannel,程序可以创建不同大小的文件,从512字节到100Mb。代码中包含了对文件大小的判断和分批写入的逻辑。

package com.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class MakeFile {

 public static long KBSIZE = 1024;
 public static long MBSIZE1 = 1024 * 1024;
 public static long MBSIZE10 = 1024 * 1024 * 10;

 public static void main(String[] args) {
  //生成的文件路径
  String path = "C:\\Documents and Settings\\Administrator\\桌面\\test.txt";
  File file = new File(path);
  try {
   file.createNewFile();
  } catch (IOException e) {
   e.printStackTrace();
  }
  //生成512字节大小文件
//  createFile(file,512);
  //生成1Kb大小文件
//  createFile(file,1024);
  //生成5Kb大小文件
//  createFile(file,1024*5);
  //生成10Kb大小文件
//  createFile(file,1024*10);
  //生成50Kb大小文件
//  createFile(file,1024*50);
  //生成100Kb大小文件
  createFile(file,1024*100);
  //生成512Kb大小文件
//  createFile(file,1024*512);
  //生成1Mb大小文件
//  createFile(file,1024*1024);
  //生成5Mb大小文件
//  createFile(file,1024*1024*5);
  //生成10Mb大小文件
//  createFile(file,1024*1024*10);
  //生成100Mb大小文件
//  createFile(file,1024*1024*100);
 }

 public static boolean createFile(File file, long fileLength) {
  FileOutputStream fos = null;
  try {
   if (!file.exists()) {
    file.createNewFile();
   }
   long batchSize = fileLength;
  /* batchSize = fileLength;
   if (fileLength > KBSIZE) {
    batchSize = KBSIZE;
   }
   if (fileLength > MBSIZE1) {
    batchSize = MBSIZE1;
   }
   if (fileLength > MBSIZE10) {
    batchSize = MBSIZE10;
   }*/
  /* long count = fileLength / batchSize;
   long last = fileLength % batchSize;
   fos = new FileOutputStream(file);
   FileChannel fileChannel = fos.getChannel();
   for (int i = 0; i < count; i++) {
    ByteBuffer buffer = ByteBuffer.allocate((int) batchSize);
    fileChannel.write(buffer);
   }
   ByteBuffer buffer = ByteBuffer.allocate((int) last);
   fileChannel.write(buffer);*/
   
   //文件内容
   String str = "1";
   //创建文件流
   fos = new FileOutputStream(file);
   //创建通道和缓冲区
            FileChannel fileChannel=fos.getChannel();
            ByteBuffer byteBuffer=ByteBuffer.allocate((int)batchSize);

   //将字符串转化为字节数组
            byte[] bytes=str.getBytes();
            for(int i = 0;i<(int) batchSize;i++){
             byteBuffer.put(bytes);
//             int position = byteBuffer.position();
            }
            byteBuffer.flip();
            fileChannel.write(byteBuffer);
   fos.close();
   return true;
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (fos != null) {
     fos.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return false;

 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值