Tải bản đầy đủ - 0 (trang)
Recipe 10.3 Closing Streams, Readers, and Writers

Recipe 10.3 Closing Streams, Readers, and Writers

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

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);



System.out.println("size:"+display);

}catch(IOExceptionioe){

System.out.println("Errorreadingfilelength.");

}



Thiscodeprintsoutthenumberofbytesintheproject.xmlfile,

andthehuman-readablesize"2KB":

File:project.xml

bytes:2132

size:2KB



Discussion

FileUtilscontainsthreestaticvariablesFileUtils.ONE_KB,

FileUtils.ONE_MB,andFileUtils.ONE_GBwhichrepresentthe

numberofbytesinakilobyte,megabyte,andgigabyte.

FileUtils.byteCountToDisplaySize()dividesthenumberof

bytesbyeachconstantuntilitfindsaconstantthatcandivide

thenumberofbytes,discardingtheremaindertocreatea

human-readablevalue.Forexample,thevalue2,123,022is

dividedbyFileUtils.ONE_GB,whichreturnsavalueofless

than1.0.ThevalueisthendividedbyFileUtils.ONE_MB,

whichreturns2thevalueusedinthehuman-readablesize"2

MB."



FileUtils.byteCountToDisplaySize()willnotroundthesizeofa

file;a2.9MBfilewillhaveadisplaysizeof2MB.Thebytecountis

dividedbyONE_KB,ONE_MB,orONE_GB,andtheremainderisdiscarded.



Recipe10.5CopyingFiles,Strings,andURLs

Problem

Youneedtocopyafiletoanotherfile,oryouneedtocopyafile

toadirectory.



Solution

UseFileUtils.copyFile()and

FileUtils.copyFileToDirectory().Thefollowingcode

copiesthefiletest.dattotest.dat.bak:

importorg.apache.commons.io.FileUtils;



try{

Filesrc=newFile("test.dat");

filedest=newFile("test.dat.bak");



FileUtils.copyFile(src,dest){

}catch(IOExceptionioe){

System.out.println("Problemcopyingfile.");

}



YoumayalsouseFileUtils.copyFileToDirectory()tocopy

afiletoadirectory.Thefollowingcodecopiesthefiletest.datto

thedirectory./temp:

try{

Filesrc=newFile("test.dat");

Filedir=newFile("./temp");



FileUtils.copyFileToDirectory(src,dir);

}catch(IOExceptionioe){

System.out.println("Problemcopyingfiletodir.");

}



Discussion

QuiteoftenyouneedtowritethecontentsofaStringtoafile.

FileUtils.writeStringToFile()providesaquickwayto

writetextualcontentstoredinaStringtoaFile,without

openingaWriter.Thefollowingcodewritesthecontentsofthe

dataStringtothefiletemp.tmp:

try{

Stringstring="Blahblahblah";



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

Recipe 10.3 Closing Streams, Readers, and Writers

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

×