Commons IO方便讀寫文件的工具類


Commons IO是apache的一個開源的工具包,封裝了IO操作的相關類,使用Commons IO可以很方便的讀寫文件,url源代碼等.

普通地讀取一個網頁的源代碼的代碼可能如下

InputStream in = new URL( "http://laoyu.info" ).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,則可以大大簡化代碼.如下:

InputStream in = new URL( "http://laoyu.info" ).openStream();
 try {
   System.out.println( IOUtils.toString( in ) );
 } finally {
   IOUtils.closeQuietly(in);
 }

Commons IO里的常用類

FileUtils包含了文件操作的相關方法.
下面的代碼用於讀取磁盤上的某個文件:

File file = new File("c:/test.txt");
List lines = FileUtils.readLines(file, "UTF-8");

FileSystemUtils 可以獲得指定磁盤路徑的可用空間

long freeSpace = FileSystemUtils.freeSpace("d:/");

文件復制代碼:

File src = new File("src.txt");
File dest = new File("dest.txt");
FileUtils.copyFile(src, dest);

補充:
方便地下載文件到本地

InputStream in = new
URL("http://www.baidu.com/img/baidu_logo.gif").openStream();
		byte [] gif = IOUtils.toByteArray(in);
		//IOUtils.write(gif,new FileOutputStream(new File("c:/test.gif")));
		FileUtils.writeByteArrayToFile(new File("c:/test.gif"),gif);
		IOUtils.closeQuietly(in);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM