Created
December 6, 2011 08:49
-
-
Save yamakk/1437429 to your computer and use it in GitHub Desktop.
ignoredecodetest.scala utf-8でdecodeできないファイルをscalaで扱う
This file contains hidden or 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
import java.io.{InputStreamReader, FileInputStream, BufferedReader} | |
import java.nio.charset.{Charset, CharsetDecoder, CodingErrorAction} | |
/* | |
通常 Source.fromFile("sample.txt")では | |
java.nio.charset.MalformedInputException: Input length = 1 | |
エラーが出る場合使う. | |
*/ | |
object IgnoreDecodeTest{ | |
val name = "sample.txt" // utf-8でdecodeできないcharactorを含むファイル | |
def main(args: Array[String]){ | |
val file = new FileInputStream(name) | |
val decoder = Charset.forName("UTF-8").newDecoder() | |
decoder.onMalformedInput(CodingErrorAction.IGNORE) | |
val reader = new BufferedReader(new InputStreamReader(file, decoder)) | |
var line = "" | |
try{ | |
while ({line = reader.readLine(); line != null}) { | |
println(line); | |
} | |
} finally{ | |
reader.close() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment