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

 时间:2026-02-14 13:07:14

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(); } } } 

  • ini配置文件中如何增加注释?
  • 如何使用SQL Developer为表新建唯一约束条件
  • idea中svn的提交、更新等操作
  • 【oracle管理】启动数据库实例
  • 离线安装sysstat包(sar命令)
  • 热门搜索
    怎么样才能快速减肥 聊城大学怎么样 混沌世界攻略 健身房减肥计划 康宝莱奶昔减肥原理 服装颜色搭配 考不上好高中怎么办 宇邦橱柜怎么样 西安工业大学怎么样 拉肚子减肥