养生 装修 购物 美食 感冒 便秘 营销 加盟 小吃 火锅 管理 创业 搭配 减肥 培训 旅游

java 写入文件时如何控制文件大小

时间:2024-09-25 15:18:06

利用byte[]函数来达到对文件大小的控制的目的。

工具/原料

Java程序

作者原创信息

http://www.iteye.com

方法/步骤

1、importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;调入相应文件

2、publicclassFileLengthextendsFile{//定义我们自己的文件,可以设置文件的最大长度longMaxLength=20;//文件的最大值为字节,默认长度Filefile;publicFileLength(Stringname){super(name);file=newFile(name);}//super(参数):调用父类中的某一个构造函数(应该为构造函数中的第一条语句)。//

3、publicvoidwrite猾诮沓靥(Filefile,byte[]b)throwsFileNotFoundException,FileOutException{File惺绅寨瞀f=file;FileOutputStreamfos;if(file.length()+b.length>MaxLength){//判断是否超过最大值,若大于就跑出FileOutExceptionthrownewFileOutException();}else{fos=newFileOutputStream(file,true);try{fos.write(b);fos.close();}catch(IOExceptione){e.printStackTrace();}}}

4、publicvoidsetLe艘绒庳焰nght(longlength){//设置我们文件的最大长度this.MaxLengt茑霁酌绡h=length;}publiclonglength(){//取到文件目前的长度returnfile.length();}classFileOutExceptionextendsException{//自定义的异常类publicStringtoString(){return"写入文件超过最大值,此操作取消!";}}publicstaticvoidmain(String[]args){FileLengthfl=newFileLength("test1.txt");//实例一个自定义的File类fl.setLenght(10);//设置我们想要文件的最大值,默认值为20字节try{fl.write(fl,"kfdjd".getBytes());//在这里测试一下System.out.println(fl.length());//打印出我们文件的长度}catch(FileNotFoundExceptione){e.printStackTrace();}catch(FileOutExceptione){e.printStackTrace();}}}

© 一点知识