java生成指定大小文件IO操作

老马过来拿
MakeFile.java

package com.zero.test;

import java.io.*;
import java.util.Date;

public class MakeFile {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
//定义文件大小的单位,1为KB,2为MB,3为GB
int unit = 0;
//定义文件的大小
int lager = 0;
//定义文件存放的分区,默认为C盘。
String partition = "C";
while (true) {
//使用Date类的getTime()得到的长整形作为文件名,防止文件名冲突
Date date = new Date();
long time = date.getTime();
//选择 文件存放分区
System.out.println("输入存放文件的分区,如想存放在C盘则输入C,D盘则是D,依次类推");
System.out.println("请确定所选分区有足够的空间存放生成的文件");
try {
line = br.readLine();
partition = line;
if(partition.length()!=1) {
System.out.println("输入错误");
continue;
}
} catch (IOException e1) {
System.out.println("输入错误");
continue;
}
FileWriter fw = null;
//新建文件
try {
fw = new FileWriter(partition+":\\"+time+".txt", true);
} catch (IOException e) {
System.out.println("输入的分区错误");
continue;
}
PrintWriter pw = new PrintWriter(fw);
//输入文件大小的单位
System.out.println("输入要生成的文件的单位,1为KB,2为MB,3为GB");
try {
line = br.readLine();

} catch (IOException e1) {
System.out.println("输入错误");
continue;
}
try {
unit = Integer.parseInt(line);
} catch (NumberFormatException e2) {
System.out.println("输入错误");
continue;
}
if(unit<0||unit>3) {
System.out.println("输入错误");
continue;
}
//输入文件的大小
System.out.println("输入要生成的文件的大小");
try {
line = br.readLine();

} catch (IOException e1) {
System.out.println("输入错误");
continue;
}
try {
lager = Integer.parseInt(line);
} catch (NumberFormatException e1) {
System.out.println("输入错误");
continue;
}
if(unit == 1) {
lager = lager*1024;
} else if (unit == 2) {
lager = lager * 1024 * 1024;
} else if (unit == 3) {
lager = lager*1024*1024*1024;
} else {
System.out.println("输入错误");
continue;
}
//开始写文件
for (int i = 0; i < lager; i++) {
pw.print(" ");
}
System.out.println("-->completed-->O(∩_∩)O~");
System.out.println("文件存放在"+partition+"盘根目录下,文件名为:"+time+".txt");
pw.close();
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值