Skip to content

Instantly share code, notes, and snippets.

@takezoux2
Created November 16, 2011 03:53
Show Gist options
  • Save takezoux2/1369189 to your computer and use it in GitHub Desktop.
Save takezoux2/1369189 to your computer and use it in GitHub Desktop.
Scala's REPL support script.You can use file easily.
import scala.io.Source
import java.io.{FileInputStream,FileOutputStream,InputStream,OutputStream,File}
import scala.xml.{XML,Elem}
// usage
// val fileAsText = "clannad.txt" loadText
// "air.txt" << "This text is written to file air.txt"
//
class FileObject( filePath : String) {
def lines : Iterator[String] = {
val source = Source.fromFile(filePath)
source.getLines
}
private def _stream[T]( func : InputStream => T) : T = {
val input = new FileInputStream(filePath)
try{
func(input)
}finally{
input.close()
}
}
private def _input[T]( func : InputStream => T) : T = {
val input = new FileInputStream(filePath)
try{
func(input)
}finally{
input.close()
}
}
def loadBytes : Array[Byte] = {
_input( input => {
val b = new Array[Byte](input.available)
input.read(b)
b
})
}
def loadText : String = loadText("utf-8")
def loadText(encoding : String) : String = {
_input( input => {
val b = new Array[Byte](input.available)
input.read(b)
new String(b,encoding)
})
}
def loadXml : Elem = {
_input(XML.load(_))
}
private def _output[T](func : OutputStream => T) : T = {
val output = new FileOutputStream(filePath)
try{
func(output)
}finally{
output.close
}
}
def <<(text : String) : Unit = {
_output(output => {
output.write(text.getBytes("utf8"))
})
}
def <<(data : Array[Byte]) : Unit = {
_output(output => {
output.write(data)
})
}
def deleteFile : Boolean = {
val f = new File(filePath)
if(f.exists){
f.delete
}else{
false
}
}
}
implicit def strToFileObj( path : String) = new FileObject(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment