IOUtils快速进行内容复制与常用方法
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                IOUtils快速进行内容复制与常用方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                今天看到項目大神寫了一個我之前沒有見過的方法,很是簡練:
IOUtils.copy(inputStream,outputStream);比起流和字節間的多行語句,這個迅速吸引了我的注意,開始學習
apache.commons.io.IOUtils
org.apache.poi.util.IOUtils
兩種大同小異,這里以第一種為例。
這里有一篇文檔寫的非常好,https://blog.csdn.net/zhoushou6/article/details/80292271
這里我把需要對比的內容復制過來
(一)打印流中信息
原始做法:new byte[] ? ? +?? .read() ? + ? new String()
File f = new File(filename);InputStream in = new FileInputStream(f);byte[] b = new byte[1024];in.read(b);System.out.println(new String(b));使用IOUtils,直接減少了咱們byte數組對象以及字節數組轉化字符串這個大步驟
File f = new File(filename);InputStream in = new FileInputStream(f);System.out.println(IOUtils.toString(in));(二)流之間的內容復制
原始狀態:被復制文件必須先轉化為比byte[],再將字節數組作為中間媒介進行二次寫入復制文件中
File f = new File(fileName1);File f2 = new File(fileName2); InputStream in=new FileInputStream(f);byte[] byteArray= new byte[1024];while(in.read()){in.read(byteArray);}OutputStream outputStream = new FileOutputStream(f2);outputStream.write(byteArray);IOUtils:
如果是很大的數據,那么可以選擇用copyLarge方法,適合拷貝較大的數據流,比如2G以上
File file1 = new File(fileName1);File file2 = new File(fileName2);InputStream inputStream2 = new FileInputStream(file2);OutputStream outputStream1 = new FileOutputStream(file1);IOUtils.copy(inputStream2,outputStream1);(三)寫入流內容
IOUtils:
IOUtils.write(“我們是幸運噠”, out);(四)關閉流
原始狀態:必要進行判斷、關流、異常捕捉
try{ if(inputStream != null){inputStream.close(); } }catch(IOException e){ }IOUtils:
IOUtils.closeQuietly(in);IOUtils.closeQuietly(out);(五)整體內容
public static void main(String[] args){File file1 = new File("jingjing.txt");File file2 = new File("xinxin.txt");String str = "連我生日都記不住";try{OutputStream outputStream = new FileOutputStream(file2);outputStream.write(str.getBytes());InputStream inputStream2 = new FileInputStream(file2);OutputStream outputStream1 = new FileOutputStream(file1);IOUtils.copy(inputStream2,outputStream1);IOUtils.closeQuietly(inputStream2);IOUtils.closeQuietly(outputStream);IOUtils.closeQuietly(outputStream1);}catch (Exception e){}}-------------------------------------------------------------------------------------------------------------------------------------------------------------
THE END
GOOD LUNCK
?
?
?
?
?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的IOUtils快速进行内容复制与常用方法的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: jQuery UI应用--滑块Slide
 - 下一篇: HTML DOM content 属性