SlidePub
Home
Categories
Login
Register
Home
General
File Handling in Java.pdf
File Handling in Java.pdf
2,516 views
19 slides
Sep 04, 2023
Slide
1
of 19
Previous
Next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
About This Presentation
https://firstcode.school/file-handling-in-java/
Size:
139.41 KB
Language:
en
Added:
Sep 04, 2023
Slides:
19 pages
Slide Content
Slide 1
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.
Slide 2
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.
Slide 3
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);
Slide 4
}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
Slide 5
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
Slide 6
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
Slide 7
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.
Slide 8
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{
Slide 9
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
Slide 10
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{
Slide 11
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
Slide 12
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.
Slide 13
■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();
}
}
}
Slide 14
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
Slide 15
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;
Slide 16
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);
}
Slide 17
}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:
Slide 18
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
Categories
General
Download
Download Slideshow
Get the original presentation file
Quick Actions
Embed
Share
Save
Print
Full
Report
Statistics
Views
2,516
Slides
19
Age
820 days
Related Slideshows
22
Pray For The Peace Of Jerusalem and You Will Prosper
RodolfoMoralesMarcuc
30 views
26
Don_t_Waste_Your_Life_God.....powerpoint
chalobrido8
32 views
31
VILLASUR_FACTORS_TO_CONSIDER_IN_PLATING_SALAD_10-13.pdf
JaiJai148317
30 views
14
Fertility awareness methods for women in the society
Isaiah47
29 views
35
Chapter 5 Arithmetic Functions Computer Organisation and Architecture
RitikSharma297999
26 views
5
syakira bhasa inggris (1) (1).pptx.......
ourcommunity56
28 views
View More in This Category
Embed Slideshow
Dimensions
Width (px)
Height (px)
Start Page
Which slide to start from (1-19)
Options
Auto-play slides
Show controls
Embed Code
Copy Code
Share Slideshow
Share on Social Media
Share on Facebook
Share on Twitter
Share on LinkedIn
Share via Email
Or copy link
Copy
Report Content
Reason for reporting
*
Select a reason...
Inappropriate content
Copyright violation
Spam or misleading
Offensive or hateful
Privacy violation
Other
Slide number
Leave blank if it applies to the entire slideshow
Additional details
*
Help us understand the problem better