[英]How to ensure that Strings are in UTF-8?
如何将此字符串the surveyÂ's rules
转换为Scala中的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编码的文本。
只需将JVM的file.encoding
参数设置为UTF-8
,如下所示:
-Dfile.encoding=UTF-8
它确保UTF-8
是默认编码。
使用scala
它可能是scala -Dfile.encoding=UTF-8
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.