如何在Scala中将此String the surveyÂ’s rules转换为UTF-8

我尝试了这些路,但没有用:

scala> val text = "the surveyÂ’s rules"
text: String = the surveyÂ’s rules

scala> scala.io.Source.fromBytes(text.getBytes(), "UTF-8").mkString
res17: String = the surveyÂ’s rules

scala> new String(text.getBytes(),"UTF8")
res21: String = the surveyÂ’s rules

好的,我以这种方式解决了。不是转换,而是简单的阅读
implicit val codec = Codec("US-ASCII").onMalformedInput(CodingErrorAction.IGNORE).onUnmappableCharacter(CodingErrorAction.IGNORE)

val src = Source.fromFile(new File (folderDestination + name + ".csv"))
val src2 = Source.fromFile(new File (folderDestination + name + ".csv"))

val reader = CSVReader.open(src.reader())

最佳答案

请注意,当您在不带参数的情况下调用text.getBytes()时,实际上您会获得一个字节数组,该字节数组表示平台默认编码中的字符串。例如,在Windows上,它可能是一些单字节编码。在Linux上,它可以已经是UTF-8。

为了正确起见,您需要在getBytes()方法调用中指定确切的编码。对于Java 7和更高版本,请执行以下操作:

import java.nio.charset.StandardCharsets

val bytes = text.getBytes(StandardCharsets.UTF_8)

对于Java 6,请执行以下操作:
import java.nio.charset.Charset

val bytes = text.getBytes(Charset.forName("UTF-8"))

然后bytes将包含UTF-8编码的文本。

关于java - 如何确保字符串在UTF-8中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23932070/

10-12 00:28
查看更多