写文件时,如何限制文件大小。

比如传入参数文件名及byte[],如果超过5M,则抛出异常显示文件太大。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileLength extends File{ //定义我们自己的文件,可以设置文件的最大长度
long MaxLength=20;//文件的最大值为字节,默认长度
File file;
public FileLength(String name) {
super(name);
file=new File(name);
}
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();
}
}
}

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

}

我们的类库里的文件类是不支持具体大小设置的,所以你如果想需要可以设置最大长度的文件,必须继承我们的文件类,然后设置最大值。自己的一点想法,参考一下

你也可以在写文件时,先判断一下file.length() +byte[].length>5M,如果大于就不能写,抛出一个自定义的异常