File Handling in Java.pdf

2,516 views 19 slides Sep 04, 2023
Slide 1
Slide 1 of 19
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19

About This Presentation

https://firstcode.school/file-handling-in-java/


Slide Content

FileHandlinginJava
Ingeneralterms,afileisacollectionofinformation.InJava,afileisanabstracttype
thatstoresrelatedinformationtogether.Thisarticlewillletyouknowaboutthefile
anditsvarioususefuloperations.Butbeforegettingtoknowaboutit,youmusthave
aclearideaaboutStreamandFileMethodsinJava.
StandardstreamsinJava:
Astreamisaseriesofdata.IthelpsusperformI/Ooperationswithafile.The
operatingsystemwilldefinethreestandardstreams.TheneedforstandardInput
andOutputusnecessary.Thisiswhereausercantakeinputfromakeyboardand
resultinproducinganoutputonthemonitor.Thoughtheinputandoutputdevices
mayvary,theprocessisthesame.InCandC++,therearethreestandarddevices
STDIN,STDOUTandSTDERR.
Itensuresthatthesestandardstreamsareaccessibleviathemembersofthe
systemclassinJava:
1.StandardInput:Itprovidesinputdatatotheprogram.Thistaskismostly
accomplishedbyakeyboardthatisusedasastandardinputstreamandisdenoted
asSystem.in.
2.StandardOutput:Itprovidestheresultofthedatathatthatprogramproduces.this
outputisusuallydisplayedonthecomputerscreenwhichisthestandardoutput
streamandisdenotedasSystem.out.

3.StandardError:Itdisplaystheerrordatathattheprogramproduces.Thisis
usuallydisplayedonthecomputerscreenthatisusedasthestandarderrorstream
andisrepresentedasSystem.err.
InputStreaminJava:
ThesuperclassofallinputstreamsistheJavaInputStreamclass.Weuseinput
deviceslikethekeyboard,network,etc.,toreadtheinput.ThisInputStreamisalso
anabstractclass.
ThevarioussubclassesoftheInputStreamclassare:
■AudioInputStream
■ByteArrayInputStream
■FileInputStream
■FilterInputStream
■StringBufferUnputStream
■ObjectInputStream
CreatinganInputStreaminjava:
InputStreamobj=newFileInputStream();
S.n
o
Method Description
1 read() Wecanusethistoreadabyteofdatefromtheinputstream.
2
read(byte[]
array)()
Itreadsabytefromthestreamandletsusstorethebyteinthe
mentionedarray.
3 mark() Itmarksthepositionintheinputstreamtillthedataisread.

4 available() Itreturnsthenumberofbytesfromtheinputstream.
5markSupported()Itchecksifthemark()methodandresult()methodinthesystem.
6 reset() Itreturnsthecontroltothepointwherethemarkwasset.
7 skips()
Itskipsandremovesthementionednumberofbytesfromtheinput
stream.
8 close() Itclosestheinputstream.
9 finalize()
Itcleanstheconnectiontothefile.Italsoensuresthattheclose
method
SampleprogramtocreateInputStreamReadertoreadthestandardinputstream
untilthecodewordforquit,‘q’isenteredbytheuser:
importjava.io.*;
publicclassFirstCodeReadConsole {
publicstaticvoidmain(Stringargs[])throwsIOException{
InputStreamReader cin=null;
try{
cin=newInputStreamReader(System.in);
System.out.println("Enterthecharacter'q'toquit.");
charc;
do{
c=(char)cin.read();
System.out.print(c);

}while(c!='q');
}finally{
if(cin!=null){
cin.close();
}
}
}
}
Output:
1
2
r
q
q
OutputstreaminJava:
Theoutputstreamgivestheabilitytowritedataintovariousoutputdevices.These
devicesincludethemonitor,printerandevenfile.OutputStreamisanabstract
superclasstorepresenttheoutputstream.
Thevarioussubclassesundertheoutputstreamclassare:
■ByteArrayOutputStream
■FileOutputStream
■StringBufferOutputStream
■DataOutputStream
■PrintStream

CreatinganOutputStream:
OutputStreamobj=newFileOutputStream();
S.N
o
Method Description
1 write() Itwritesthespecifiedbytetotheoutputstream.
2
write(byte[]
array)
Itwritesthebyteswhicharegiveninaspecificarraytotheoutput
stream
3 close() Itclosestheoutputstream
4 flush()
Itforcestowriteallthedatapresentinanoutputstreamtoits
destination
5 finalize()
Itcleanstheconnectiontothefile.Itensuresthattheclosemethodifthe
fileoutstreamisinvokedintheabsenceofotherreferencestothe
stream.
OutputStreamsOperationsinJava:
Therearethreemethodstowritethedataintoastream.Thesemethodsare
availableintheIndependentoutputstream.Thesemirrortheread()methods
presentintheInputStreamClass,whichisalsoanabstractclass.
OutputStreamsOperations Description
FileOutputStream Towriteafile

ObjecyInputStream Towriteobjectstoastream
ByteArrayOutputStream Towriteanarrayofbytes
PipeOutputStream Towritetoapipedstream
FilterOutputStream Tofiltertheoutputfromanendstream
Basedonthedatatype,thestreamisdividedintotwocategories:
1.ByteStream
2.CharacterStream
ClassificationofI/Ostreamsinjava:
1.ByteStream:
ByteStreamtakesplacewithbytedata.Inthistypeoffilehandlingmethod,thebyte
streamprocessallowsexecutionwithbytedata.
2.CharacterStream:
Ittakesplacewithcharacterdata.Inthistypeoffilehandlingmethod,thecharacter
streamprocessallowsexecutionwithcharacterdata.
JavaFileClassMethods:
S.N
o
Method
Return
Type
Description

1 canRead()Boolean
Usingthismethod,wecancheckifthefilecanbe
readornot.
2createNewFile()BooleanWecanusethismethodtocreateanewfile.
3 canWrite()BooleanItletsuscheckifwecanwriteinthefileornot.
4 exists()Boolean
Itisusedtocheckifthementionedfileisavailable
ornot.
5 delete()Boolean Usingthismethod,wecandeleteafile.
6 getName()String
Wecanusethismethodtofindthenameofthe
file.
7
getAbsolutePath
()
String
Thismethodhelpsusinknowingtheabsolute
pathnameofthefile.
8 length()Long Itletsusattainthesizeofthefilesinbytes
9 list()String[]
Usingthismethod,wecangetthearrayoffilesin
thedirectory
10 mkdir()BooleanWecanusethismethodtocreateanewdirectory
WhatisFilehandlinginJava?
Filehandlingistheprocessofreadingandwritingdataintoafile.TheFileclassin
Javaispresentinthejava.iopackage.Wecansimplyusethefileclassbycreating
anobjectfortheclassandspecifyingthenameofthefileordirectory.

WhyisFilehandlingrequired?
Tobeginwith,letusfirstunderstandtheimportanceofthisconcept.
Filehandlingisanintegralpartofeveryprogramminglanguage.Storingtheoutput
ofaprograminafileformatmakesiteasilyretrievable.Therefore,filehandlingisan
essentialpartofprogramming.
JavaFileOperations:
Thevariousoperationsthatwecanperforminafileinjavaarelistedbelow:
■Creatingafile
■Gettingfileinformation
■Writingintoafile
■Readingfromafile
■Deletingafile
1.FilecreationinJava:
TheFileCreationoperationletsuscreateanewfile.Themethodthatperformsthis
actionisthecreateNewFile()method.Itreturnstrueaftersuccessfullycreatinga
newfile.Ifthefieldnamealreadyexists,thismethodreturnsfalse.
SampleprogramtocreateafileinJava:
importjava.io.File;
importjava.IOException;
classFirstCode{
publicstaticvoidmain(Stringargs[]){
try{

Filef()=newFile(“D:CreatingFileExample. txt”);
if(f().createNewFile()){
System.out.println(“Thefile”+f().getName()+“iscreatedsuccefully.”);
}else{
System.out.println(“Thefilenamealreadyexistsinthedirectory”);
}
}catch(IOExceptionexception){
System.out.println(“Error!!!”);
exception.printStackTrace();
}
}
}
2.Readfromafile/GetFileInformation:
Weperformthisoperationtoretrievethedatafromthefile.Someofthemethods
thatletusachievethisarename,absolutepath,isreadable,iswriteableandlength.
Sampleprogramtoreadinformationfromafile:
importjava.io.File;
classFirstCode{
publicstaticvoidmain(Stringargs[]){
Filef()=newFile(“D:ReadingFileExample. txt”);
if(f().exists()){
System.out.println(“Thefilenameis:”+f()getName());//togetfilename

System.out.println(“Theabsolutepathis:”+f().getAbsolutepath());//togetfile
path
//tocheckitthefileiswriteableornot
System.out.println(“Isthefilewriteable?”+f().canWrite());
//tocheckifthefileisreadableornot
System.out.println(“Isthefilereadable?”+f().canRead());
//togetthelengthofthefile
System.out.println(“Thesizeofthefileinbytesis:”+f().length());
}else{
System.out.println(“Thefiledoesnotexist”);
}
}
}
3.Writeintoafile:
Towriteintoafile,weusetheFileWriterclassandthewrite()method.Thestream
shouldbeclosedusingtheclose()methodtoretrievetheresources.
Sampleprogramtowriteintoafile:
importjava.io.FileWriter;
importjava.io.IOException;
classFirstCode{
publicstaticvoidmain(Stringargs[]){
try{

FileWriterfwrite=newFileWriter(“D:FileWritingExample. txt”);
fwrite.write(“LearnJavawithFirstCode”);
fwrite.close();
System.out.println(“Contentissuccessfullywritteninthefile”);
}
catch(IOExceptione){
System.out.println(“Error!!!”);
e.printStackTerrace();
}
}
}
JavaFileWriter:
ThisclassinJavahelpstheprogrammerstocreatenewfilewritingcharacters.It
inheritsfromtheOutputStreamclass.
Theconstructorspresentinthisclassgenerallyassumethatthebyte-buffersizeand
defaultcharacterencodingareacceptable.Todeclaretheseconstructors,wemust
constructOutputStreamWriteronaFileOutputStream.
TheJavaFileWriterisverymuchusefulforwritingstreamsof
characters.constructors
4.Readfromafileinjava:
Toreadthecontentpresentinthefile,weneedtousetheScannerclass.The
streamisclosedusingtheclose()method.WecancreateanobjectfortheScanner

classtoimplementthehasNextLine()andnextLine()methods.Thesemethods
retrievetheinformationfromthefile.
JavaFileReader:
TheFileReaderinJavaplaysavitalroleinreadingthedatathatispresentinthe
formofcharacters.Thisisdoneintheformofa‘text’file.TheFileReaderinherits
fromtheInputStreamReaderclass.
Theconstructorsinthisclassassumethedefaultcharacterencodingandthedefault
byteareappropriate.AstheJavaFileReaderisusedonlyforparticularlyreading
streamsofcharacter,youcanusetheFileInputStreamtoreadstreamsofrawbytes.
Methods:
Methods Description
publicintread()throws
IOException
Thismethodreadasinglecharacterandblocksoneuntil
anotheroneisavailable.Thatis,aninput/outputerror
occurs.
publicintread(char[]cbuff[])
throwsIOException
Itreadscharactersintoanarrayandblocksuntila
characterisavailable.
publicabstractintread(char[]
buff,intoff,intlen)whichthrows
anIOException
Itreadcharactersintoaportionofanarray.Itblocksuntil
theinputisavailableoranerroroccursintheinputand
output,ortheendofthestreamisreached.
Parameters:
■cbuff–Destinationbuffer.
■off–Itsetstheoffsetatwhichtostartstoringcharacters.
■len–itusestoseethemaximumnumberofcharacterstoread.

■publiclongskip(longn)throwsIOException:Itskipsthecharactersand
blocksuntilsomecharactersareavailable,anI/Oerroroccursorthe
streamendisreached.
Sampleprogramtoreadfromafile:
importjava.io.File;
importjava.io.FileNotFoundException ;
importjava.util.Scanner;
classFirstCode{
publicstaticvoidmain(Stringargs[]){
try{
Filef=newFile(“D:ReadFromFile.txt”);
Scanners=newScanner(f);
while(s.hasNextLine()){
StringfileData=s.nextLine();
System.out.println(fileData);
}
s.close();
}catch(FileNotFoundException exception){
System.out.println(“Error!!!”);
exception.printStackTrace();
}
}
}

Deletingafile:
Knowingtodeleteafileisasimportantascreatingone.Thedelete()method
performsthistask.Weneednotclosethestreamwiththeclose()methodorusethe
FileWriterandScannerclasshere.
Sampleprogramtodeleteafile:
importjava.io.File;
classFirstCode{
publicstaticvoidmain(Stringargs[]){
Filef()=newFile(“D:DeletingFile.txt”);
if(f().delete()){
System.out.println(f().getname()+“Thefileisdeleted”);
}else{
System.out.println(“Error!!!”);
}
}
}
JavaDirectories:
Methodstocreateandmodifyfilesanddirectoriesin
java:
Methods Description

renameTo(File
path)
Thefilethatthecurrentobjectrepresentswillberenamedtothepaththat
thefileobjectpassesasanargumenttothemethod.
setreadonly()
Itsetsthefilesthatrepresentthecurrentobjectasread-onlyandreturns
truewhenthetaskissucceeded.
mkdir() Itcreatesadirectorywiththepathspecifiedbythecurrentfileobject.
mkdirs()
Createsthedirectoryrepresentedbythecurrentfileobject,including
parentdirectoriesthatarerequired.
createanewfile()
Itcreatesanewemptyfilewithapathnamedefinedbythecurrentfile
objectaslongasthefileexists.
delete()
Thisdeletesthefileinadirectoryrepresentedbythecurrentfileobjectand
returnstrueifthedeleteissuccessful.
createDirectory(Path,FileAttribute</>)
CreatingDirectoriesinjava:
JavaprovidesacoupleofbeneficialFileutilitymethodsthatareusedtocreate
directories.
■Themkdir()methodcreatesadirectory.Itreturnstrueforsuccessand
falseforfailure.Thefailuredenotesthatthepaththatismentionedinthe
Fileobjectexistsalready.Italsodenotesthatthedirectorycannotbe
createdifthepathdoesnotexist.
■Themkdirs()methodscreatebothadirectoryandalsoparentsofthe
directory.
Sampleprogramtocreateadirectory:
importjava.io.File;

publicclassCreateDirFirstCode{
publicstaticvoidmain(Stringargs[]){
Stringdirname="/tmp/user/java/bin" ;
Filed=newFile(dirname);
d.mkdirs();
}
}
ListingdirectoriesinJava
TheFileobjectprovidesthelist()methodtolistdownallthefilesanddirectoriesthat
arepresent.
Sampleprogramtolistthedirectories:
importjava.io.File;
publicclassReadDirFirstCode {
publicstaticvoidmain(String[]args){
Filefile=null;
String[]paths;
try{
file=newFile("/tmp");
paths=file.list();
for(Stringpath:paths){
System.out.println(path);
}

}catch(Exceptione){
e.printStackTrace();
}
}
}
Output:
test1.txttest2.txt
ReadDir.java
ReadDir.class
QueryingFilesandDirectoriesinJava:
Method Description
exists()
Itreturnsifthefileordirectoryreferredtobythefileobjectexistsandfalse
otherwise
isfile() Itreturnsifthefileobjectreferstoanexistingfileandfalseotherwise.
canread()Itreturnstrueifitallowsreadingthesilethatisreferredbythefileobject.
canwrite(
)
Itreturnstrueifyouarepermittedtowritethefilereferredbythefileobject.
Constructors:

Constructors Description
FileWriter(Filefile)
ThisconstructorconstructsaFileWriterobject
whenafileobjectisgiven.
FileWriter(Filefile,booleanappend)ItconstructsanobjectforFilewriter.
FileWriter(FileDescriptorfd)
ConstructsaFileWriterobjectassociatedusing
afiledescriptor.
FileWriter(StringfileName)
ItconstructsaFileWriterobjectwhenafile
nameisgiven.
publicvoidwrite(intc)throwsIOExceptionItwritesasinglecharacter.
publicvoidwrite(char[]stir)throws
IOException
Itwritesanarrayofcharacter.
publicvoidwrite(Stringstr)throws
IOException
ItwritesastringinJava.
FileWriter(Stringfilename,Booleanappend)
ItconstructsaFileWriterobjectwhenafile
nameispresent.
publicvoidwrite(Stringstr,intoff,intlen)
throwsIOException
ItwritesaportionofaString.
Conclusion:
Thisarticlewouldhavehelpedyouinknowingvariousdetailsaboutfilehandlingin
Java.Youcannowcreateyourownfileandperformvariousfilehandlingoperations
toit.Thisletsyoustorethedataandretrievethemeasily.
Tags