【问题标题】:Java―read, process and write UTF-8 fileJava——读取、处理和写入UTF-8文件
【发布时间】:2013-09-24 16:20:45
【问题描述】:

我正在尝试编写一些读取可能存在编码错误的 UTF-8 编码文件、处理内容并将结果写入也以 UTF-8 编码的输出文件的内容。

我的程序应该修改内容(搜索和替换的种类),然后一一复制其余的内容。换句话说:如果要搜索的词等于要替换的词,则输入文件和输出文件也应该相等。

一般我使用这个代码:

in = Paths.get( <filename1> );
out = Paths.get( <filename2> );

Files.deleteIfExists( out );
Files.createFile( out );

CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
decoder.onMalformedInput( CodingErrorAction.IGNORE );
decoder.onUnmappableCharacter( CodingErrorAction.IGNORE );

BufferedReader reader = new BufferedReader( 
    new InputStreamReader(
        new FileInputStream( this.in.toFile() ), decoder ) );

CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
encoder.onMalformedInput( CodingErrorAction.IGNORE );
encoder.onUnmappableCharacter( CodingErrorAction.IGNORE );

BufferedWriter writer = new BufferedWriter( 
    new OutputStreamWriter(
        new FileOutputStream( this.out.toFile() ), encoder) );

char[] charBuffer = new char[100];
int readCharCount;
StringBuffer buffer = new StringBuffer();

while( ( readCharCount = reader.read( charBuffer ) ) > 0 )
{
    buffer.append( charBuffer, 0, readCharCount );
    //here goes more code to process the content
    //buffer must be written to output on each iteration
}

writer.write( buffer.toString() );
reader.close();
writer.close();

但这不起作用。为了比较文件,我有这个失败的小 JUnit 测试:

byte[] bytesf1 = Files.readAllBytes( Paths.get( <filename1> ) );
byte[] bytesf2 = Files.readAllBytes( Paths.get( <filename2> ) );
assertTrue( bytesf1.equals( bytesf2 ) ); 

我做错了什么,或者我该怎么做才能使它正常工作?

在此先感谢您, 菲利普

编辑

除非我能在确保我的输入文件以 UTF-8 编码后设法使测试工作,否则基本错误是什么,我真正的兴趣点和问题是:

上述方法是否保证 UTF-8 文件中的缺陷也被一对一复制,或者将字符加载到 Stringbuffer 中的过程是否会改变这一点?

【问题讨论】:

  • 您的文件是否包含字节顺序标记(BOM)??
  • 好问题!我怎样才能知道呢?结果似乎很安静,只是有些字符不同……
  • 你能在你的测试用例中使用 Arrays.equals(bytesf1, bytesf2) 而不是 bytesf1.equals( bytesf2 )
  • 我可以,我做到了,但仍然测试失败......
  • grep -rl $'\xEF\xBB\xBF' --> 不匹配,所以我猜没有BOM

标签: java encoding utf-8 io copy


【解决方案1】:

Java 数组不实现基于值的equals。这总是会失败:

assertTrue( bytesf1.equals( bytesf2 ) ); 

考虑:

assertArrayEquals(bytesf1, bytesf2);

assertTrue(Arrays.equals(bytesf1, bytesf2));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-07
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多