1. 程式人生 > >【跟我學apache-commons】【四】commons-io的使用

【跟我學apache-commons】【四】commons-io的使用

commons-io是一款處理io流的工具,封裝了很多處理io流和檔案的方法,可以大大簡化我們處理io流和操作檔案的程式碼。從common-io的官方使用文件可以看出,它主要分為工具類、尾端類、行迭代器、檔案過濾器、檔案比較器和擴充套件流。

官網地址:http://commons.apache.org/proper/commons-io/

下載 :http://commons.apache.org/proper/commons-io/download_io.cgi

一、工具類

工具類包括FileUtils、IOUtils、FilenameUtils和FileSystemUtils,前三者的方法並沒有多大的區別,只是操作的物件不同,故名思議:FileUtils主要操作File類,IOUtils主要操作IO流,FilenameUtils則是操作檔名,FileSystemUtils包含了一些JDK沒有提供的用於訪問檔案系統的實用方法。當前,只有一個用於讀取硬碟空餘空間的方法可用。例項如下

FileUtils的使用:

package com.wj.test;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class FileUtilsTest {

	private String basePath = null;

	@Before
	public void setUp() {
		basePath = System.getProperty("user.dir") + "\\file\\";
	}

	@After
	public void tearDown() throws Exception {
	}

	/**
	 * 拷貝檔案
	 * @throws IOException
	 */
	@Test
	public void testCopy() throws IOException {
		File srcFile = new File(basePath + "a.txt");
		File destFile = new File(basePath + "b.txt");
		FileUtils.copyFile(srcFile, destFile);
	}
	
	/**
	 * 刪除檔案
	 * @throws IOException
	 */
	@Test
	public void testDelete() throws IOException{
		File delFile = new File(basePath + "b.txt");
		FileUtils.forceDelete(delFile);
		//FileUtils.forceMkdir(delFile);
	}
	
	/**
	 * 比較檔案內容
	 * @throws IOException
	 */
	@Test
	public void testCompareFile() throws IOException{
		File srcFile = new File(basePath + "a.txt");
		File destFile = new File(basePath + "b.txt");
		boolean result = FileUtils.contentEquals(srcFile, destFile);
		System.out.println(result);
	}
	
	/**
	 * 移動檔案
	 * @throws IOException
	 */
	@Test
	public void testMoveFile() throws IOException{
		File srcFile = new File(basePath + "b.txt");
		File destDir = new File(basePath + "move");
		FileUtils.moveToDirectory(srcFile, destDir, true);
	}
	
	/**
	 * 讀取檔案內容
	 * @throws IOException
	 */
	@Test 
	public void testRead() throws IOException{
		File srcFile = new File(basePath + "a.txt");
		String content = FileUtils.readFileToString(srcFile);
		List<String> contents = FileUtils.readLines(srcFile);
		System.out.println(content);
		System.out.println("******************");
		for (String string : contents) {
			System.out.println(string);
		}
	}
	
	/**
	 * 寫入檔案內容
	 * @throws IOException
	 */
	@Test
	public void testWrite() throws IOException{
		File srcFile = new File(basePath + "a.txt");
		FileUtils.writeStringToFile(srcFile, "\nyes檔案", true);
	}
	
}
FileSystemUtils的使用:
package com.wj.test;

import java.io.IOException;

import org.apache.commons.io.FileSystemUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class FileSystemUtilsTest {
	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	/**
	 * 獲取磁碟空餘空間
	 * @throws IOException
	 */
	@SuppressWarnings("deprecation")
	@Test
	public void testFreeSpace() throws IOException {
		// 以位元組為單位
		System.out.println(FileSystemUtils.freeSpace("c:\\") / 1024 / 1024 / 1024);
		System.out.println(FileSystemUtils.freeSpace("d:\\") / 1024 / 1024 / 1024);
		// 以k為單位
		System.out.println(FileSystemUtils.freeSpaceKb("e:\\") / 1024 / 1024);
		System.out.println(FileSystemUtils.freeSpaceKb("f:\\") / 1024 / 1024);
		
	}

}

二、尾端類

不同的計算機體系結構使用不同約定的位元組排序。在所謂的“低位優先”體系結構中(如Intel),低位位元組處於記憶體中最低位置,而其後的位元組,則處於更高的位置。在“高位優先”的體系結構中(如Motorola),這種情況恰恰相反。

這個類庫上有兩個相關類:

EndianUtils包含用於交換java原物件和流之間的位元組序列。

SwappedDataInputStream類是DataInput介面的一個例項。使用它,可以讀取非本地的位元組序列。

三、行迭代器

org.apache.commons.io.LineIterator類提供了一個靈活的方式與基於行的檔案互動。可以直接建立一個例項,或者使用FileUtils或IOUtils的工廠方法來建立,例項如下:

package com.wj.test;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class LineIteratorTest {
	
	private String basePath = null;

	@Before
	public void setUp() throws Exception {
		basePath = System.getProperty("user.dir") + "\\file\\";
	}

	@After
	public void tearDown() throws Exception {
	}
	
	/**
	 * 測試行迭代器
	 * @throws IOException
	 */
	@Test
	public void testIterator() throws IOException{
		File file = new File(basePath + "a.txt");
		LineIterator li = FileUtils.lineIterator(file);
		while(li.hasNext()){
			System.out.println(li.nextLine());
		}
		LineIterator.closeQuietly(li);
	}

}


四、檔案過濾器

org.apache.commons.io.filefilter包定義了一個合併了java.io.FileFilter以及java.io.FilenameFilter的介面(IOFileFilter)。除此之外,這個包還提供了一系列直接可用的IOFileFilter的實現類,可以通過他們合併其它的檔案過濾器。比如,這些檔案過濾器可以在列出檔案時使用或者在使用檔案對話方塊時使用。例項如下:

package com.wj.test;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.filefilter.EmptyFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class FileFilterTest {
	
	private String basePath = null;

	@Before
	public void setUp() throws Exception {
		basePath = System.getProperty("user.dir") + "\\file\\";
	}

	@After
	public void tearDown() throws Exception {
	}
	
	/**
	 * 空內容檔案過濾器
	 * @throws IOException
	 */
	@Test
	public void testEmptyFileFilter() throws IOException{
		File dir = new File(basePath);
		String[] files = dir.list(EmptyFileFilter.NOT_EMPTY);
		for (String file : files) {
			System.out.println(file);
		}
	}
	
	/**
	 * 檔名稱字尾過濾器
	 * @throws IOException
	 */
	@Test
	public void testSuffixFileFilter() throws IOException{
		File dir = new File(basePath);
		String[] files = dir.list(new SuffixFileFilter("a.txt"));
		for (String file : files) {
			System.out.println(file);
		}
	}

}

五、檔案比較器

org.apache.commons.io.comparator包為java.io.File提供了一些java.util.Comparator介面的實現。例如,可以使用這些比較器對檔案集合或陣列進行排序。例項如下:

package com.wj.test;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.comparator.CompositeFileComparator;
import org.apache.commons.io.comparator.DirectoryFileComparator;
import org.apache.commons.io.comparator.NameFileComparator;
import org.apache.commons.io.comparator.PathFileComparator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class ComparatorTest {

	private String basePath = null;

	@Before
	public void setUp() throws Exception {
		basePath = System.getProperty("user.dir") + "\\file\\";
	}

	@After
	public void tearDown() throws Exception {
	}

	/**
	 * 檔名稱比較器
	 * @throws IOException
	 */
	@Test
	public void testNameFileComparator() throws IOException {
		File f1 = new File(basePath + "a.txt");
		File f2 = new File(basePath + "c.txt");
		int result = NameFileComparator.NAME_COMPARATOR.compare(f1, f2);
		System.out.println(result);
	}

	/**
	 * 檔案路徑比較器
	 * @throws IOException
	 */
	@Test
	public void testPathFileComparator() throws IOException {
		File f1 = new File(basePath + "a.txt");
		File f2 = new File(basePath + "c.txt");
		int result = PathFileComparator.PATH_COMPARATOR.compare(f1, f2);
		System.out.println(result);
	}

	/**
	 * 組合比較器
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@Test
	public void testCompositeFileComparator() throws IOException {
		File dir = new File(basePath);
		File [] files = dir.listFiles();
		for (File file : files) {
			System.out.println(file.getName());
		}
		CompositeFileComparator cfc = new CompositeFileComparator(
				DirectoryFileComparator.DIRECTORY_COMPARATOR,
				NameFileComparator.NAME_COMPARATOR);
		cfc.sort(files);
		System.out.println("*****after sort*****");
		for (File file : files) {
			System.out.println(file.getName());
		}
	}
}

六、擴充套件流

org.apache.commons.io.input和org.apache.commons.io.output包中包含的針對資料流的各種各樣的的實現。包括:

  • 空輸出流-默默吸收發送給它的所有資料
  • T型輸出流-全用兩個輸出流替換一個進行傳送
  • 位元組陣列輸出流-這是一個更快版本的JDK類
  • 計數流-計算通過的位元組數
  • 代理流-使用正確的方法委拖
  • 可鎖寫入-使用上鎖檔案提供同步寫入
  • 等等