Java读取,处理和写入UTF-8文件

时间:2013-09-24 16:20:45

标签: java encoding utf-8 io copy

我正在尝试编写一些读取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的过程是否会更改?

1 个答案:

答案 0 :(得分:1)

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

assertTrue( bytesf1.equals( bytesf2 ) ); 

考虑:

assertArrayEquals(bytesf1, bytesf2);

assertTrue(Arrays.equals(bytesf1, bytesf2));
相关问题