手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

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

时间:2024-10-11 23:03:49

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

2、public class FileLength extends File{ //定义我们自己的文件,可以设置文件的最大长度long MaxLength=20;//文件的最大值为字节,默认长度File file; public FileLength(String name) {super(name);file=new File(name);} //super(参数):调用父类中的某一个构造函数(应该为构造函数中的第一条语句)。//

3、public void write猾诮沓靥(File file,byte[] b) throws FileNotFoundException,FileOutException {File f=file;FileOutputStream fos;if(file.length()+b.length>MaxLength) {//判断是否超过最大值,若大于就跑出FileOutExceptionthrow new FileOutException();}else{fos=new FileOutputStream(file,true);try {fos.write(b);fos.close();} catch (IOException e) {e.printStackTrace();}}}

4、public void setLe艘绒庳焰nght(long length) { //设置我们文件的最大长度this.MaxLengt茑霁酌绡h=length;}public long length(){ //取到文件目前的长度return file.length();}class FileOutException extends Exception{ //自定义的异常类public String toString() {return "写入文件超过最大值,此操作取消!";}}public static void main(String[] args) {FileLength fl=new FileLength("test1.txt"); //实例一个自定义的File类fl.setLenght(10); //设置我们想要文件的最大值,默认值为20字节try {fl.write(fl,"kfdjd".getBytes());//在这里测试一下System.out.println(fl.length()); //打印出我们文件的长度} catch (FileNotFoundException e) {e.printStackTrace();} catch (FileOutException e) {e.printStackTrace();}}}

© 手抄报圈