我正在从数据库加载一些文本并将其写入文件。如果我从Eclipse内部运行我的程序一切正常,但如果我用Maven打包程序,我得到一个UnmappableCharacterException
。
我创建了一个BufferedWriter
,如下所示:
final BufferedWriter writer = Files.newBufferedWriter(csvFile, StandardCharsets.ISO_8859_1);
当我致电writer.flush
时,会抛出异常。
这是堆栈跟踪:
java.nio.charset.UnmappableCharacterException: Input length = 1
at java.nio.charset.CoderResult.throwException(Unknown Source)
at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at java.io.BufferedWriter.flushBuffer(Unknown Source)
at java.io.BufferedWriter.flush(Unknown Source)
at com.siemens.okhbimporter.importers.NodeWriter.run(NodeWriter.java:85)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
我只将字符串传递给write()
方法。如果我将字符集设置为UTF-8,一切正常。这是怎么回事?
错误发生在字符串Knoten;1;1;false;Fügetechnik;;2003-06-11 00:00:00;2003-06-11 00:00:00;
。我看不到ISO-8859-1中没有的字符。
答案 0 :(得分:1)
Files.newBufferedWriter返回一个抛出UnmappableCharacterException(报告编码错误)的Writer,但您可以创建一个写入Path的BufferedWriter,并使用Files.newOutputStream替换错误的输入。例如下面的代码
class WorkFile < ActiveRecord::Base
has_attached_file :attachment,
:styles => { :small => "150x150#"},
:url => "/assets/work_files/:id/:style/:basename.:extension",
:path => ":rails_root/app/assets/images/work_files/:id/:style/:basename.:extension"
validates_attachment_content_type :attachment, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
validates_attachment_size :attachment, :less_than => 1.megabytes
end
输出“espa?ol”。