Created
December 30, 2008 21:28
-
-
Save p3t0r/41762 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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