Created
June 23, 2012 04:49
-
-
Save anvie/2976913 to your computer and use it in GitHub Desktop.
File Appender in Scala
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
/* | |
* Copyright (c) 2012 Ansvia Inc. | |
* Author: robin | |
*/ | |
package com.ansvia.rootr.storage | |
import java.io.{FileWriter, BufferedWriter, File} | |
/** | |
* File appender is logger like engine | |
* that allow you to store data to a file by appending. | |
* The write operation using buffered writer where | |
* every write buffered and flushing after `max` count. | |
* If file doesn't exists, file appender will created one | |
* otherwise file appender will just open a file in append mode. | |
* @param filePath file path to write. | |
* @param max max count where data will be flushed. | |
*/ | |
class FileAppender(filePath:String, max:Int=5) { | |
private val maxFlushCount = max | |
private var count = 0 | |
private lazy val writer:BufferedWriter = { | |
val f = new File(filePath) | |
if (!f.exists()){ | |
f.createNewFile() | |
} | |
new BufferedWriter(new FileWriter(f, true)) | |
} | |
/** | |
* Write string into file. | |
* @param str string to write. | |
*/ | |
def write(str:String){ | |
writer.write(str) | |
count += 1 | |
if (count > maxFlushCount){ | |
writer.flush() | |
count = 0 | |
} | |
} | |
/** | |
* Write string into file with trailing new line. | |
* @param str string to write. | |
*/ | |
def writeln(str:String){ | |
writer.write(str) | |
writer.newLine() | |
count += 1 | |
if (count > maxFlushCount){ | |
writer.flush() | |
count = 0 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment