月曜日, 4月 01, 2013

Commons IO FileUtils

また Commons IO

前回のCommons Lang StringUtilsに引き続き,Commons IO FileUtilsの紹介..
StringUtilsに負けず劣らずニッチを上手く扱っている上,使い勝手が良い.

Version 2.4を使うとして,Mavenのdependencyは

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

Gradleならば

'commons-io:commons-io:2.4'

Grapesであれば

@Grapes(
@Grab(group='commons-io', module='commons-io', version='2.4')
)

便利なメソッド群

Javadocを一瞥してみると,便利そうなメソッドがすぐ見つかるだろう.実際使い勝手は良い.

いくつかをピックアップして試してみたコードは以下の通り.
FileUtils無しに同じコードを書いたとすれば沢山のStream系オブジェクトの扱い及び例外処理だらけのコードになるであろうことは想像に難くない.

import java.io.File;

import static org.hamcrest.CoreMatchers.*;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import static org.apache.commons.io.FileUtils.*;


public class FileUtilTest {

@Test
public void testReadWrite() throws Exception {
File tmpFile = null;
File tmpFile2 = null;
File tmpFile3 = null;
try {
tmpFile = File.createTempFile( "tmp", "test" );
           // write() .. write string to file
                        // sizeOf() .. checks file size
write( tmpFile, "1\n2\n" );
assertThat( sizeOf( tmpFile ), is( 4L ) );

                        // readLine() .. read lines from files and persist them to List<String>
int lineNum = 1;
for( String line : readLines( tmpFile ) ) {
assertThat( Integer.parseInt( line ), is( lineNum++ ) );
}
                        // readFileToString() .. read file and returns its content as single string
assertThat( "1\n2\n", is( readFileToString( tmpFile ) ) );
tmpFile2 = File.createTempFile( "tmp", "test" );

                        // write() .. write string to file
write( tmpFile2, "1\n2\n" );
                        // contentEquals() .. compare two files each other
                        // contentEqualsIgnoreEOL .. compare two files each other and ignore EOL
contentEquals( tmpFile, tmpFile2 );
tmpFile3 = File.createTempFile( "tmp", "test" );
write( tmpFile3, "1\r\n2\r\n" );
contentEqualsIgnoreEOL( tmpFile, tmpFile3, null );
} finally {
                        // forceDelete() .. delete file or directory in force manner ( it means delete all recursively )
forceDelete( tmpFile );
forceDelete( tmpFile2 );
forceDelete( tmpFile3 );
}
}
}

0 件のコメント: