Groovy笔记(8)_File
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类的其他常用方法
? 写多个对象到文件的方法 ? ? 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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |