如何确保字符串是UTF-8?

YoB*_*Bre 7 java scala utf-8 character-encoding

如何将此String转换the surveyÂ’s rulesUTF-8Scala?

我尝试过这些道路,但不起作用:

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
Run Code Online (Sandbox Code Playgroud)

好的,我已经以这种方式解决了.不是转换,而是简单的阅读

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())
Run Code Online (Sandbox Code Playgroud)

Vla*_*eev 9

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

要正确,您需要在getBytes()方法调用中指定确切的编码.对于Java 7及更高版本,请执

import java.nio.charset.StandardCharsets

val bytes = text.getBytes(StandardCharsets.UTF_8)
Run Code Online (Sandbox Code Playgroud)

对于Java 6,执行以下操作:

import java.nio.charset.Charset

val bytes = text.getBytes(Charset.forName("UTF-8"))
Run Code Online (Sandbox Code Playgroud)

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


Nit*_*tul 5

只需将JVM的file.encoding参数设置UTF-8为如下:

-Dfile.encoding=UTF-8
Run Code Online (Sandbox Code Playgroud)

它确保这UTF-8是默认编码.

使用scala它可能是scala -Dfile.encoding=UTF-8.