File 类介绍
1、抽象路径名:File类提供抽象的,独立于系统的分级路径名试图。
D:/clat/test.groovy(注意抽象路径名使用/,不是/ )
2、File可以表示文件或目录
3、Groovy对java.io.File进行了增强(参考GDK Doc)
def toysFile = new File("src/TestToysFile.dat")
if(!toysFile.exists()){
toysFile.createNewFile()
toysFile.append('Groovy and clat' + '/n')
}
4、File类的其他常用方法
- Boolean delete():删除文件或目录
- void eachFile(Closure cl):目录中每个文件应用闭包
- void eachFileResurse(Closure cl):同上并对子目录递归
- void eachLine(Closure cl):逐行遍历文件并应用闭包
- String getPath():将抽象路径名称转换为路径名字符串。
- String getText():读文件返回字符串
- Boolean isDirectory():是否目录
- Boolean mkdir():创建目录
- void withPrintWriter(Closure cl):获取打印速写器。//具体不明,可以查API
写多个对象到文件的方法
1、基础知识:将对象序列化到文件时,如果多个对象序列化到同一个文件,会覆盖头部信息,使得读取对象失败,所以要做处理。
2、
public class FileObjectOutputStream extends ObjectOutputStream{
private File file;
private boolean append;
//构造函数
public FileObjectOutputStream() throws IOException,Exception{}
public FileObjectOutputStream(File file) throew IOException,Exception{this(file,false);}
public FileObjectOutputStream(File file,boolean append) throws IOException, Exception{
supre(new FileOutputStream(file,append));
this.file = file;
this.append = append;
}
//当文件中有对象时覆盖writeStreamHeader()方法,以便Reset流的头部信息
protected void writeStreamHeader()throew IOException{
System.out.println("/t/tReset Stream Header!")
super.reset();
}
}
3、Demo
def toysFile = new File("src/testToysFile.dat")
if(!toysFile.existe()){
toysFile.createNewFile()
toysFile.append('Groovy hello!')
}
def newToy = new Toy(toyName:'toy',unitPrice:'100')
def objOutput
if(toysFile.length() == 0 ){ // 如果文件时新的 则新建
objOutput = new ObjectOutputStream(new FileOutputStream(toysFile, true))
}else{ //如果文件已经被写过需要特殊处理
objOutput = new FileObjectOutputStream(toysFile, true)
}
objOutput.writeObject(new Toy1)
objOutput.flush();
objOutput.close()
读取文件
1、
def objInput
try{
objInput = new ObjectInputStream(new FileInputStream(toysFile))
def obj = objInput.readObject()
while(obj){
prinltn obj.toyName + ':' + obj.unitPrice
obj = objInput.readObject()
}
}catch(EOFException e){}
if(objInput !=null){
objInput.close()
}
多删几次文件
1、基础知识:Java中删除文件不一定成功,所有策略是多删除几次。
2、
def forceDeleteFile(File file){
Boolean result = false
def delCount = 0
while(!result && delCount ++ <10){
System.gc()
result = file.delete()
}
return result
}