我正在使用以下代码读取资源:

  val source = Source.fromResource(pathWithoutSlash)
  val lines:Seq[String] = (for (l <- source.getLines() if ! l.trim.isEmpty) yield l.trim).toList

当我在本地运行该代码时,它工作正常-但在服务器上,它失败并显示:
Exception in thread "main" java.nio.charset.MalformedInputException: Input length = 1
    at java.base/java.nio.charset.CoderResult.throwException(CoderResult.java:274)
    at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339)
    at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    at java.base/java.io.InputStreamReader.read(InputStreamReader.java:185)
    at java.base/java.io.BufferedReader.fill(BufferedReader.java:161)
    at java.base/java.io.BufferedReader.readLine(BufferedReader.java:326)
    at java.base/java.io.BufferedReader.readLine(BufferedReader.java:392)
    at scala.io.BufferedSource$BufferedLineIterator.hasNext(BufferedSource.scala:70)

我猜是因为文件确实包含一些重音字符,例如:éclair's,并且服务器上使用的默认字符集可能与我本地的字符集不同。

我的问题是,如何更改服务器上的字符集,使其与我本地拥有的字符集匹配(以及如何检查本地拥有的字符集)?

谢谢。

最佳答案

我假设您可以看到的隐式 Codec

println(implicitly[scala.io.Codec])

在您的服务器上是不同的。如果我正确理解,它应该评估为scala.io.Codec.fallbackSystemCodec。只需显式传递适当的Codec( fromResource 方法在第二个参数列表中采用隐式Codec即可),例如:
val source = Source.fromResource(pathWithoutSlash)(Codec.UTF8)

09-28 02:16