以下是使用例子:
当我们要读取一个URL的内容的时候通常会这么写:
InputStream in = new URL( "http://jakarta.apache.org" ).openStream();
try {
InputStreamReader inR = new InputStreamReader( in );
BufferedReader buf = new BufferedReader( inR );
String line;
while ( ( line = buf.readLine() ) != null ) {
System.out.println( line );
}
} finally {
in.close();
}
而使用commons.io里的IOutil类之后可以简单地
System.out.println( IOUtils.toString( inURL ) );
或者想要将url内容写到文件里,
FileUtils.copyURLToFile( srcURL, destFile );
再比如将一个流输入复制到另一个流,一句
IOUtils.copy( inputStream, outputStream );
再比如只想写一个字符串到文件里去的话,只要
FileUtils.writeStringToFile( destFile, string);
或者以字节方式读入文件
byteArray = Fileutil.readFileToByteArray(File file) ;
同样也有writeByteArrayToFile,readFileToString等等
还有数据间的复制,CopyUtil可以将InputStream,Reader,byte[]数据或字符串的内容拷贝到OutputStream或Writer,应该大部分需求都能满足了。
Fileutil包括用来读、写、复制、比较文件的各种方法
按行读文件:
File file = new File("/commons/io/project.properties"); List lines = FileUtils.readLines(file, "UTF-8");
LineIterator it = FileUtils.lineIterator(file, "UTF-8"); while (it.hasNext()) { String line = it.nextLine();
其他的还有检查checksum,处理文件名、系统空间、大小端、文件过滤器、清除目录、纪录字节数的流、输出到两个流的流等等,这些详细功能就等用到再去看doc吧