How to skip invalid characters in stream in Java/Scala?

前端 未结 4 1641
面向向阳花
面向向阳花 2021-02-02 12:53

For example I have following code

Source.fromFile(new File( path), \"UTF-8\").getLines()

and it throws exception

Exception in         


        
4条回答
  •  礼貌的吻别
    2021-02-02 13:16

    If you want to avoid invalid characters using Scala, I found this worked for me.

    import java.nio.charset.CodingErrorAction
    import scala.io._
    
    object HelloWorld {
    
      def main(args: Array[String]) = {
        implicit val codec = Codec("UTF-8")
    
        codec.onMalformedInput(CodingErrorAction.REPLACE)
        codec.onUnmappableCharacter(CodingErrorAction.REPLACE)
    
        val dataSource = Source.fromURL("https://www.foo.com")
    
        for (line <- dataSource.getLines) {
    
          println(line)
        }
      }
    }
    

提交回复
热议问题