Tải bản đầy đủ - 0 (trang)
Recipe 10.2 Copying Streams, byte[ ], Readers, and Writers

Recipe 10.2 Copying Streams, byte[ ], Readers, and Writers

Tải bản đầy đủ - 0trang

inputStream.close();

}catch(IOExceptione){

System.out.println("Errorcopyingdata");

}



Thepreviousexamplereadstest.resourceusingan

InputStream,whichiscopiedtoaFileWriterusing

CopyUtils.copy().



Discussion

IfyouneedtocopyinformationfromaReaderorInputStream

toaString,useIOUtils.toString().Thefollowingexample

opensanInputStreamfromaURLandcopiesthecontentstoa

String:

importorg.apache.commons.io.IOUtils;



URLurl=newURL("http://www.slashdot.org");

try{

InputStreaminStream=url.openStream();

Stringcontents=IOUtils.toString(inStream);

System.out.println("Slashdot:"+contents);



}catch(IOExceptionioe){

//handlethisexception

}



BecauseCopyUtilsusesa4KBbuffertocopybetweenthe

sourceandthedestination,youdonotneedtosupplybuffered

streamsorreaderstothecopy()method.Whenusing

CopyUtils.copy(),makesuretoflush()andclose()any

streams,Readers,orWriterspassedtocopy().



Recipe10.3ClosingStreams,Readers,andWriters

Problem

YouneedtocloseanInputStream,OutputStream,Reader,orWriter,andyou

wanttoavoidcatchinganIOExceptioninafinallyblock.



Solution

UseIOUtils.closeQuietly()tocloseanInputStream,OutputStream,Reader,

orWriterwithouthavingtotestfornullordealwithanIOException.The

followingcodedemonstratestheuseofcloseQuietly()toavoidanasty

try/catchwithinafinallyblock:

importorg.apache.commons.io.IOUtils

importorg.apache.commons.io.CopyUtils



Readerreader=null;

Stringresult="":



try{

Filefile=newFile("test.dat");

reader=newFileReader(file);

result=CopyUtils.toString(reader);

}catch(IOExceptionioe){

System.out.println("Unabletocopyfiletest.dattoaString.");

}finally{

IOUtils.closeQuietly(reader);

}




Day

Up>



Recipe10.4PrintingaHuman-ReadableFileSize

Problem

Youneedtodisplaythesizeofafileinkilobytes,megabytes,or

gigabytes.Insteadofdisplayingfilesizesas1,073,741,824

bytes,youwantanapproximate,human-readablesize,suchas

1GB.



Solution

UseFileUtils.byteCountToDisplaySize()toproducea

Stringcontaininganapproximate,human-readablesize.The

followingcodepassesthenumberofbytesinthefile

project.xmltoFileUtils.byteCountToDisplaySize():

importorg.apache.commons.io.FileUtils;



try{

Filefile=newFile("project.xml");

longbytes=file.length();



Stringdisplay=FileUtils.byteCountToDisplaySize(bytes);

System.out.println("File:project.xml");

System.out.println("bytes:"+bytes);



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Recipe 10.2 Copying Streams, byte[ ], Readers, and Writers

Tải bản đầy đủ ngay(0 tr)

×