Skip to content

Instantly share code, notes, and snippets.

@p3t0r
Created December 30, 2008 21:28
Show Gist options
  • Save p3t0r/41762 to your computer and use it in GitHub Desktop.
Save p3t0r/41762 to your computer and use it in GitHub Desktop.
package com.maasfrensch
import java.io._
/**
* Adds some useful methods to file, to be used implicitely:
* implicit def file2enhanced(file:File) = new EnhancedFile(file)
* @author [email protected]
*/
class EnhancedFile(val file:File) {
def readLines(block: String => Unit) = EnhancedFile.readLines(file, block)
def asString = EnhancedFile.asString(file)
}
object EnhancedFile {
def readLines(file:File, block: String => Unit) = {
var reader = new BufferedReader(new FileReader(file));
manage(reader) {
var thisLine:String = ""
var line:String = reader.readLine
while (line != null) {
block(line)
line = reader.readLine
}
}
}
def process(source:File, target:File, block: String => String) = {
var reader = new BufferedReader(new FileReader(source))
var writer = new BufferedWriter(new FileWriter(target))
manage(reader, writer) {
var thisLine:String = ""
var line:String = reader.readLine
while (line != null) {
var res = block(line)
writer.write(res)
writer.newLine
line = reader.readLine
}
}
}
def asString(file:File):String = {
val data = new StringBuilder()
readLines(file, data.append(_).append("\n"))
data.toString
}
private type Closeable = { def close() }
private def manage(closeables: Closeable*)(block: => Unit) = {
try {
block
} finally {
closeables.foreach({closeable =>
try{
closeable.close()
} catch {
case t:Throwable => t.printStackTrace
}
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment