importscala.io._importjava.io.{FileNotFoundException,IOException}valfilename="no-such-file.scala"try{for(line<-Source.fromFile(filename).getLines){println(line)}}catch{casee:FileNotFoundException=>println("Couldn't find that file.")casee:IOException=>println("Got an IOException!")}
finally{
filename.close
}
valfile=newFile(canonicalFilename)valbw=newBufferedWriter(newFileWriter(file))bw.write(text)bw.close()
2. Read and write binary files in Scala
importjava.io._objectCopyBytesextendsApp{varin=None:Option[FileInputStream]varout=None:Option[FileOutputStream]try{in=Some(newFileInputStream("/tmp/Test.class"))out=Some(newFileOutputStream("/tmp/Test.class.copy"))varc=0while({c=in.get.read;c!=−1}){out.get.write(c)}}catch{casee:IOException=>e.printStackTrace}finally{println("entered finally ...")if(in.isDefined)in.get.closeif(out.isDefined)out.get.close}}
No comments:
Post a Comment