Scala ERROR java.nio.charset.MalformedInputException: Input length = 1
import scala.io.Source
object Test{
def main(args: Array[String] ){
val filename = "test.txt"
Source.fromFile("test.txt", "UTF-8").foreach{
print
}
}
}
在執行上段程式碼的時候,遇到了 java.nio.charset.MalformedInputException: Input length = 1 的錯誤,官方解釋這個錯誤為:
MalformedInputException thrown when an input byte sequence is not legal for given charset, or an input character sequence is not a legal sixteen-bit Unicode sequence.
代表輸入時遇到不合法的字元,所以只要把輸入的字元編碼就可以了。
fromFile 方法有提供編碼的參數:
fromFile (name : java.lang.String, enc : java.lang.String) : Source
creates Source from file with given name, using given encoding, setting its description to filename.
所以改成:
object Test{
def main(args: Array[String] ){
val filename = "test.txt"
Source.fromFile("test.txt", "UTF-8").foreach{
print
}
}
}
沒有留言:
張貼留言