在下面的例子,我們將詳細說明如何使用 org.apache.commons.io 包中的 IOUtils類如何使用,通過包名我們可以知道它是 Apache Commons IO 的一部分 。該類的所有成員函數都被用來處理輸入 - 輸出流,它的確非常利於來編寫處理此類事務的程序。IOUtils與其他Apache Commons中的類一樣,都是處理IO操作的非常重要包裝器,與手動編寫這些功能的其他程序相比,它們實現這些方法的代碼變得更小,更清晰,更易理解。
1. IOUtils類,字段和方法簡介
IOUtils類的所有成員字段和方法都是靜態的,因此在標准編程中不需要創建IOUtils類的對象,而是通過類名和適當的方法名來使用它。如:IOUtils.method1 ()。
2. IOUtils 字段
static char DIR_SEPARATOR:目錄分隔符
static char DIR_SEPARATOR_UNIX:Unix系統的目錄分隔符
static char DIR_SEPARATOR_WINDOWS:Windows系統的目錄分隔符
static String LINE_SEPARATOR:行分隔符
static String LINE_SEPARATOR_UNIX:Unix系統的行分隔符
static String LINE_SEPARATOR_WINDOWS:Windows系統的行分隔符
3. IOUtils 方法摘要
現在我們將要討論的是IOUtils中的一些非常重要的方法。類中的所有處理InputStream的方法都帶有內部的緩沖區,所以我們不需要再使用 BufferedReader或者 BufferedInputStream,默認的緩沖區大小為4K,不過我們也可以自定義它的大小。
static void closeQuietly(Closeable closeable):它將無條件的關閉一個可被關閉的對象而不拋出任何異常。它也有很多版本去支持關閉所有的InputStream、OutputStream、Reader和Writer。
static boolean contentEquals(Reader inp1,Reader inp2):這個方法將比較兩個Reader對象的內容是否相同,相同返回true,否則返回false。它還有另外的一個版本去比較InputStream對象。還有一個方法 contentEqualsIgnoreEOL(Reader r1,Rrader r2),它將忽略行結束符而比較內容。
static int copy(InputStream inp,OutputStream outp):這個方法將內容按字節從一個InputStream對象復制到一個OutputStream對象,並返回復制的字節數。同樣有一個方法支持從Reader對象復制到Writer對象。
static LineIterator lineIterator(InputStream input,String enc):這個方法將從InputStream中返回一個行迭代器,我們可以指定一個字符格式(或者為空而使用默認的)。行迭代器將持有一個打開的InputStream的引用。當你迭代結束后,應當關閉stream來釋放內部資源。這個字符編碼也可以是一個字符集對象。同樣也有一個方法支持Reader對象。
static List<String> readLines(InputStream inp,String enc)
static List<String> readLines(Reader inp)
static BufferedReader toBufferedReader(Reader rdr, int size)
static InputStream toInputStream(CharSequence inp, String enc)
static String toString(Reader inp)
static void write(String data,Writer outp)
static void writeLines(Collection<?> lines,String lineEnding,Writer outp)
4. 方法使用
IOUtils.toInputStream()方法
InputStream is=IOUtils.toInputStream("This is a String","utf-8");
IOUtils.toInputStream()方法為*“This is a String”*創建一個InputStream,並返回該對象。
IOUtils.closeQuietly()方法
public void test2() throws IOException { InputStream is=IOUtils.toInputStream("This is a String","utf-8"); OutputStream os=new FileOutputStream("test2.txt"); int bytes=IOUtils.copy(is,os); System.out.println("File Written with "+bytes+" bytes"); IOUtils.closeQuietly(os); }
我們可以方便的關閉輸出流而不用拋出異常,我們打開它的源碼看看:
@Deprecated public static void closeQuietly(final Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (final IOException ioe) { // ignore } }
可見,它跟我們傳統的關閉輸出流是一樣的,沒什么區別,不過我們可以看見它已經被廢棄了,現在推薦的是利用Java7引入的 try-with-resources方式來關閉。
@Test public void test2() throws IOException { try (InputStream is = IOUtils.toInputStream("This is a String", "utf-8"); OutputStream os = new FileOutputStream("test2.txt")) { int bytes = IOUtils.copy(is, os); System.out.println("File Written with " + bytes + " bytes"); } }
更多關於 try-with-resources可以看 try-with-resources 和 multi-catch
IOUtils.copy()方法
public void test2() throws IOException { try (InputStream is = IOUtils.toInputStream("This is a String", "utf-8"); OutputStream os = new FileOutputStream("test2.txt")) { int bytes = IOUtils.copy(is, os); System.out.println("File Written with " + bytes + " bytes"); } }
IOUtils.copy()方法有很多版本,我這里舉例的是最常用的方法,同時還有一個IOUtils.copyLarge()方法支持復制(不超過2GB)的InputStream或者Reader對象。
IOUtils.toString()方法
FileReader fileReader = new FileReader("test2.txt")); System.out.println(IOUtils.toString(fileReader));
和上面所看到的toString方法類似,IOUtils有支持 InputStream、URI和 URL的方法,它們都需要指定字符集。
IOUtils.read()方法
@Test public void test4(){ try(FileInputStream fin=new FileInputStream("test2.txt")){ byte[] buf= new byte[100]; int len=IOUtils.read(fin,buf); System.out.println("The Length of Input Stream:"+len); }catch (IOException e){ e.printStackTrace(); } }
該方法從InputStream中讀取bytes並返回一個byte[]。之后我們可以對該byte[]數組進行操作。有些時候該方法非常有用,但是我們建議使用readlines()方法。
IOUtils.writeLines()方法
@Test public void test5() { try (FileInputStream fin = new FileInputStream("test2.txt")) { List ls = IOUtils.readLines(fin, "utf-8"); for (int i = 0; i < ls.size(); i++) { System.out.println(ls.get(i)); } } catch (IOException e) { e.printStackTrace(); } }
我們可以將InputStream的內容作為字符串列表,然后對其進行操作。
IOUtils.writeLines()方法
@Test public void test6(){ List<String> ls=new ArrayList<>(); ls.add("asdasd"); ls.add("ada21"); ls.add("addsf"); try(OutputStream os=new FileOutputStream("test3.txt")) { IOUtils.writeLines(ls,IOUtils.LINE_SEPARATOR_WINDOWS,os); } catch (IOException e) { e.printStackTrace(); } }
LineIterator 類和 lineIterator() 方法
@Test public void test7(){ try(FileInputStream fin=new FileInputStream("test2.txt")){ LineIterator lt=IOUtils.lineIterator(fin,"utf-8"); while (lt.hasNext()){ String line=lt.nextLine(); System.out.println(line); } }catch (IOException e){ e.printStackTrace(); } }
通過lineIterator方法返回一個LineIterator對象,然后進行迭代。
IOUtils.write()方法
@Test public void test8(){ try(OutputStream os=new FileOutputStream("test4.txt")){ IOUtils.write("sahjsdhjad",os,"utf-8"); }catch (IOException e){ e.printStackTrace(); } }
我們可以通過IOUtils.write()方法將String寫到一個Writer對象或者OutputStream對象中去。
其他代碼參考:
1.從流中讀取數據
FileInputStream fileInputStream = new FileInputStream(new File("d://demo.txt")); List<String> list = IOUtils.readLines(fileInputStream, "UTF-8");//只要是InputStream流都可以,比如http響應的流 //直接把流讀取為String String content = IOUtils.toString(inputStream,"UTF-8"); //把流轉換為byte數組 byte[] bytes = IOUtils.toByteArray(inputStream);
2.把數據寫入流
//把數據寫入輸出流 IOUtils.write("abc", outputStream); //把字符串轉換流 InputStream inputStream = IOUtils.toInputStream("aaaaaaaaa", "UTF-8");
2.流的相互復制
IOUtils.copy(inputstream,outputstream);
IOUtils.copy(inputstream,writer);
IOUtils.copy(inputstream,writer,encoding);
IOUtils.copy(reader,outputstream);
IOUtils.copy(reader,writer);
IOUtils.copy(reader,writer,encoding);
2.流的關閉
try { return IOUtils.copy(inputStream, outputStream); } finally { //優雅的關閉流 IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); }
鏈接:https://www.jianshu.com/p/6b4f9e5e2f8e
鏈接:https://blog.csdn.net/l2580258/article/details/89227761