Skip to content

Instantly share code, notes, and snippets.

@yamakk
Created December 6, 2011 08:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yamakk/1437429 to your computer and use it in GitHub Desktop.
Save yamakk/1437429 to your computer and use it in GitHub Desktop.
ignoredecodetest.scala utf-8でdecodeできないファイルをscalaで扱う
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