java 写入文件时如何控制文件大小
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) {//判断是否超过最大值,若大于就跑出FileOutException throw new FileOutException(); }else{ fos=new FileOutputStream(file,true); try { fos.write(b); fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
4、public void setLenght(long length) { //设置我们文件的最大长度 this.MaxLength=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(); } } }