SlideShare a Scribd company logo
Lecture 11
File handling
File Handling
File Handling
▪ File class – creating objects for files
▪ Specify the file name (assume the current directory) or the
directory and file name to the constructor.
▪ exists() method returns true if the file exists.
File myFile = new File("someFile.dat");
File myFile = new File("D:Documents","someFile.dat");
File Handling
▪ Can also associate the File object with a directory instead:
▪ If it is a directory, then the list() method will return an array
of Strings of all the files in the directory.
▪ isFile() method returns true if it is associated with a File,
false if associated with a directory.
File myDir = new File("D:Documents");
File Handling
▪ There is also a GUI object that can be used to select files or
directories (from the javax.swing.* package)
JFileChooser choose = new JFileChooser();
int status = choose.showOpenDialog(null);
File Handling
▪ The returned value from showOpenDialog() tells us whether or
not the “open” button was clicked. It returns an int value,
JFileChooser.APPROVE_OPTION if the “open” button was clicked.
▪ If it was, we can use the getSelectedFile() method or the
getCurrentDirectory() method to get the selected file or
directory.
▪ Lots of other methods with File class and JFileChooser class
that have been omitted.
File Handling
▪ Now that we have the file, we have to input to and
output from the file.
▪ We can do low-level File I/O or high-level File I/O.
▪ In order to do either of these, we need a stream object.
▪ Streams are simply sequences of data items.
– Need streams for input and streams for output.
▪ NOTE: the method that is doing file handing needs to
handle an IOException or needs to throw it back to the
calling method.
public static void main(String[] args) throws IOException{
Low level file handling
File Handling
Low level file output
▪ Start by creating a File object:
▪ Next, create a FileOutputStream object and associate it
with the File object.
File myFile = new File("someFile.dat");
FileOutputStream outStream = new FileOutputStream(myFile);
File Handling
Low level file output
▪ At this stage all we can send to the stream is a
sequence of bytes:
▪ After we are done writing, we need to close the stream:
byte[] byteStream = {2, 92, 17, 64, 9};
outStream.write(byteStream);
outStream.close();
File Handling
Low level file input
▪ Again, create a File object. Also create a
FileInputStream object and associate with the File
object.
▪ We are going to read into a byte array, so we need to
set it up. The length of the array will be the length of
File object
File myFile = new File("someFile.dat");
FileInputStream inStream = new FileInputStream(myFile);
int fileLength = (int) myFile.length();
byte[] byteStream = new byte[fileLength];
File Handling
Low level file input
int fileLength = (int) myFile.length();
byte[] byteStream = new byte[fileLength];
inStream.read(byteStream);
File Handling
Low level file input/output
File
FileInputStream
File
FileOutputStream
High level file handling
File Handling
▪ Writing and reading individual bytes is tedious if we are
not working with byte-sized data.
▪ Java gives us another layer of stream objects that
handle the conversion from other data types to the byte
array.
File Handling
High level file output
▪ Still need the FileOutputStream object, but now we
don’t interact with it directly
▪ Instead use a DataOutputStream object, associate it with
the FileOutputStream object
▪ DataOutputStream object allows us to write primitive
data types.
File myFile = new File("someFile.dat");
FileOutputStream outStream = new FileOutputStream(myFile);
DataOutputStream outDataStream = new DataOutputStream(outStream);
File Handling
▪ Now, we can write any primitive data type using the
DataOutputStream objects:
outDataStream.writeDouble(...);
outDataStream.writeFloat(...);
outDataStream.writeLong(...);
outDataStream.close();
File Handling
High level file input:
▪ Set up File object, FileInputStream object and
DataInputStream object.
▪ Use the read methods of the DataInputStream objects to
read from the file.
File myFile = new File("someFile.dat");
FileInputStream inStream = new FileInputStream(myFile);
DataInputStream inDataStream = new DataInputStream(inStream);
double myDouble = inDataStream.readDouble();
float myFloat = inDataStream.readFloat();
long myLong = inDataStream.readLong();
inDataStream.close();
File Handling
High level file input/output:
File
DataOutputStream
FileOutputStream
writeFloat()
writeDouble()
writeInt()
File
DataInputStream
FileInputStream
readFloat()
readDouble()
readInt()
File Handling
▪ FileOutputStream and FileInputStream objects have
been useful for reading and writing primitive variables.
▪ But for text files:
▪ Use PrintWriter instead of DataOutputStream
▪ Use FileReader instead of FileInputStream
▪ Use BufferedReader instead of DataInputStream
File Handling
High level text file output:
▪ Set up File object, FileOutputStream object and
PrintWriter object.
▪ Use the println() methods to write to the file – can
write any primitive data type which is then converted to
a String.
File myFile = new File("someTextFile.txt");
FileOutputStream outStream = new FileOutputStream(myFile);
PrintWriter outPrintStream = new PrintWriter(outStream);
outPrintStream.println(99.0);
outPrintStream.println("123");
outPrintStream.close();
File Handling
High level text file input:
▪ Set up File object, FileReader object and BufferedReader
object.
▪ Use the readLine() methods to read from the file – everything
is read as a String, convert to other type if necessary
File myFile = new File("someTextFile.txt");
FileReader inFileReader = new FileReader(myFile);
BufferedReader inBufferedReader = new BufferedReader(inFileReader);
String line = inBufferedReader.readLine();
inBufferedReader.close();
File Handling
High level text file input:
▪ We can also use the Scanner class, and associate it directly to
a file, instead of associating it with the console
▪ Use Scanner methods to read and automatically convert
File myFile = new File("someTextFile.txt");
Scanner scanFile = new Scanner(myFile);
String s = scanFile.next();
Double d = scanFile.nextDouble();
Boolean b = scanFile.nextBoolean();
File Handling
High level text file input/output:
File
PrintWriter
FileOutputStream
println()
File
BufferedRead
FileReader
readLine()
File
Scanner
next() nextInt()
nextFloat()
File Handling
▪ What about reading and writing objects?
▪ We can read and write the individual data members
using a Data Stream
▪ Better to use ObjectOutputStream and
ObjectInputStream objects.
▪ Note: to write an object, we need to add to its class
definition:
▪ But we don’t need to do anything else – no compulsory
methods to write…
class Student implements Serializable
File Handling
High level object file output:
▪ Set up File object, FileOutputStream object and
ObjectOutputStream object.
▪ Write using the writeObject() method:
File myFile = new File("someFile.dat");
FileOutputStream outStream = new FileOutputStream(myFile);
ObjectOutputStream outObjStream = new ObjectOutputStream(outStream);
Student s = new Student();
outObjStream.writeObject(s);
File Handling
High level object file input:
▪ Set up File object, FileInputStream object and
ObjectInputStream object.
▪ Use the readObject methods to read from the file. Note: we
need to cast the object to the correct object class.
▪ We can read and write objects from different classes in one file.
File myFile = new File("someFile.dat");
FileInputStream inStream = new FileInputStream(myFile);
ObjectInputStream inObjectStream = new ObjectInputStream(inStream);
Student s;
s = (Student) inObjectStream.readObject();
File Handling
High level - object
File
ObjectOutputStream
FileOutputStream
writeObject()
File
ObjectInputStream
FileInputStream
readObject()

More Related Content

Similar to Lecture 11.pdf (20)

PDF
Java Day-6
People Strategists
 
PPTX
File Handling in Java Oop presentation
Azeemaj101
 
PDF
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
PDF
File Handling in Java.pdf
SudhanshiBakre1
 
PPTX
Input output files in java
Kavitha713564
 
PPT
Comp102 lec 11
Fraz Bakhsh
 
PDF
Programming language JAVA Input output opearations
2025183005
 
PPTX
Java Input Output (java.io.*)
Om Ganesh
 
PDF
Java IO Stream, the introduction to Streams
ranganadh6
 
PPTX
File Input and output.pptx
cherryreddygannu
 
PPTX
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
PPS
Files & IO in Java
CIB Egypt
 
PDF
Files in java
Muthukumaran Subramanian
 
PPT
Java Input Output and File Handling
Sunil OS
 
PDF
26 io -ii file handling
Ravindra Rathore
 
PPT
Itp 120 Chapt 19 2009 Binary Input & Output
phanleson
 
DOCX
FileHandling.docx
NavneetSheoran3
 
Java Day-6
People Strategists
 
File Handling in Java Oop presentation
Azeemaj101
 
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
File Handling in Java.pdf
SudhanshiBakre1
 
Input output files in java
Kavitha713564
 
Comp102 lec 11
Fraz Bakhsh
 
Programming language JAVA Input output opearations
2025183005
 
Java Input Output (java.io.*)
Om Ganesh
 
Java IO Stream, the introduction to Streams
ranganadh6
 
File Input and output.pptx
cherryreddygannu
 
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
Files & IO in Java
CIB Egypt
 
Java Input Output and File Handling
Sunil OS
 
26 io -ii file handling
Ravindra Rathore
 
Itp 120 Chapt 19 2009 Binary Input & Output
phanleson
 
FileHandling.docx
NavneetSheoran3
 

More from SakhilejasonMsibi (11)

PDF
Lecture 6.pdf
SakhilejasonMsibi
 
PDF
Lecture 4 part 2.pdf
SakhilejasonMsibi
 
PDF
Lecture2.pdf
SakhilejasonMsibi
 
PDF
Lecture3.pdf
SakhilejasonMsibi
 
PDF
Lecture 7.pdf
SakhilejasonMsibi
 
PDF
Lecture 5.pdf
SakhilejasonMsibi
 
PDF
Lecture 8.pdf
SakhilejasonMsibi
 
PDF
Lecture 9.pdf
SakhilejasonMsibi
 
PDF
Lecture 4 part 1.pdf
SakhilejasonMsibi
 
PDF
Lecture 10.pdf
SakhilejasonMsibi
 
PDF
Lecture1.pdf
SakhilejasonMsibi
 
Lecture 6.pdf
SakhilejasonMsibi
 
Lecture 4 part 2.pdf
SakhilejasonMsibi
 
Lecture2.pdf
SakhilejasonMsibi
 
Lecture3.pdf
SakhilejasonMsibi
 
Lecture 7.pdf
SakhilejasonMsibi
 
Lecture 5.pdf
SakhilejasonMsibi
 
Lecture 8.pdf
SakhilejasonMsibi
 
Lecture 9.pdf
SakhilejasonMsibi
 
Lecture 4 part 1.pdf
SakhilejasonMsibi
 
Lecture 10.pdf
SakhilejasonMsibi
 
Lecture1.pdf
SakhilejasonMsibi
 

Recently uploaded (20)

PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
PDF
Water Design_Manual_2005. KENYA FOR WASTER SUPPLY AND SEWERAGE
DancanNgutuku
 
PDF
UNIT-4-FEEDBACK AMPLIFIERS AND OSCILLATORS (1).pdf
Sridhar191373
 
PDF
monopile foundation seminar topic for civil engineering students
Ahina5
 
PPTX
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
PDF
6th International Conference on Machine Learning Techniques and Data Science ...
ijistjournal
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
PDF
Statistical Data Analysis Using SPSS Software
shrikrishna kesharwani
 
PPTX
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PDF
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
PDF
IoT - Unit 2 (Internet of Things-Concepts) - PPT.pdf
dipakraut82
 
PPT
Oxygen Co2 Transport in the Lungs(Exchange og gases)
SUNDERLINSHIBUD
 
PPTX
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 
PPTX
MPMC_Module-2 xxxxxxxxxxxxxxxxxxxxx.pptx
ShivanshVaidya5
 
PPTX
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPTX
Pharmaceuticals and fine chemicals.pptxx
jaypa242004
 
PPTX
Types of Bearing_Specifications_PPT.pptx
PranjulAgrahariAkash
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
Water Design_Manual_2005. KENYA FOR WASTER SUPPLY AND SEWERAGE
DancanNgutuku
 
UNIT-4-FEEDBACK AMPLIFIERS AND OSCILLATORS (1).pdf
Sridhar191373
 
monopile foundation seminar topic for civil engineering students
Ahina5
 
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
6th International Conference on Machine Learning Techniques and Data Science ...
ijistjournal
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
Statistical Data Analysis Using SPSS Software
shrikrishna kesharwani
 
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
IoT - Unit 2 (Internet of Things-Concepts) - PPT.pdf
dipakraut82
 
Oxygen Co2 Transport in the Lungs(Exchange og gases)
SUNDERLINSHIBUD
 
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 
MPMC_Module-2 xxxxxxxxxxxxxxxxxxxxx.pptx
ShivanshVaidya5
 
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
Pharmaceuticals and fine chemicals.pptxx
jaypa242004
 
Types of Bearing_Specifications_PPT.pptx
PranjulAgrahariAkash
 

Lecture 11.pdf

  • 3. File Handling ▪ File class – creating objects for files ▪ Specify the file name (assume the current directory) or the directory and file name to the constructor. ▪ exists() method returns true if the file exists. File myFile = new File("someFile.dat"); File myFile = new File("D:Documents","someFile.dat");
  • 4. File Handling ▪ Can also associate the File object with a directory instead: ▪ If it is a directory, then the list() method will return an array of Strings of all the files in the directory. ▪ isFile() method returns true if it is associated with a File, false if associated with a directory. File myDir = new File("D:Documents");
  • 5. File Handling ▪ There is also a GUI object that can be used to select files or directories (from the javax.swing.* package) JFileChooser choose = new JFileChooser(); int status = choose.showOpenDialog(null);
  • 6. File Handling ▪ The returned value from showOpenDialog() tells us whether or not the “open” button was clicked. It returns an int value, JFileChooser.APPROVE_OPTION if the “open” button was clicked. ▪ If it was, we can use the getSelectedFile() method or the getCurrentDirectory() method to get the selected file or directory. ▪ Lots of other methods with File class and JFileChooser class that have been omitted.
  • 7. File Handling ▪ Now that we have the file, we have to input to and output from the file. ▪ We can do low-level File I/O or high-level File I/O. ▪ In order to do either of these, we need a stream object. ▪ Streams are simply sequences of data items. – Need streams for input and streams for output. ▪ NOTE: the method that is doing file handing needs to handle an IOException or needs to throw it back to the calling method. public static void main(String[] args) throws IOException{
  • 8. Low level file handling
  • 9. File Handling Low level file output ▪ Start by creating a File object: ▪ Next, create a FileOutputStream object and associate it with the File object. File myFile = new File("someFile.dat"); FileOutputStream outStream = new FileOutputStream(myFile);
  • 10. File Handling Low level file output ▪ At this stage all we can send to the stream is a sequence of bytes: ▪ After we are done writing, we need to close the stream: byte[] byteStream = {2, 92, 17, 64, 9}; outStream.write(byteStream); outStream.close();
  • 11. File Handling Low level file input ▪ Again, create a File object. Also create a FileInputStream object and associate with the File object. ▪ We are going to read into a byte array, so we need to set it up. The length of the array will be the length of File object File myFile = new File("someFile.dat"); FileInputStream inStream = new FileInputStream(myFile); int fileLength = (int) myFile.length(); byte[] byteStream = new byte[fileLength];
  • 12. File Handling Low level file input int fileLength = (int) myFile.length(); byte[] byteStream = new byte[fileLength]; inStream.read(byteStream);
  • 13. File Handling Low level file input/output File FileInputStream File FileOutputStream
  • 14. High level file handling
  • 15. File Handling ▪ Writing and reading individual bytes is tedious if we are not working with byte-sized data. ▪ Java gives us another layer of stream objects that handle the conversion from other data types to the byte array.
  • 16. File Handling High level file output ▪ Still need the FileOutputStream object, but now we don’t interact with it directly ▪ Instead use a DataOutputStream object, associate it with the FileOutputStream object ▪ DataOutputStream object allows us to write primitive data types. File myFile = new File("someFile.dat"); FileOutputStream outStream = new FileOutputStream(myFile); DataOutputStream outDataStream = new DataOutputStream(outStream);
  • 17. File Handling ▪ Now, we can write any primitive data type using the DataOutputStream objects: outDataStream.writeDouble(...); outDataStream.writeFloat(...); outDataStream.writeLong(...); outDataStream.close();
  • 18. File Handling High level file input: ▪ Set up File object, FileInputStream object and DataInputStream object. ▪ Use the read methods of the DataInputStream objects to read from the file. File myFile = new File("someFile.dat"); FileInputStream inStream = new FileInputStream(myFile); DataInputStream inDataStream = new DataInputStream(inStream); double myDouble = inDataStream.readDouble(); float myFloat = inDataStream.readFloat(); long myLong = inDataStream.readLong(); inDataStream.close();
  • 19. File Handling High level file input/output: File DataOutputStream FileOutputStream writeFloat() writeDouble() writeInt() File DataInputStream FileInputStream readFloat() readDouble() readInt()
  • 20. File Handling ▪ FileOutputStream and FileInputStream objects have been useful for reading and writing primitive variables. ▪ But for text files: ▪ Use PrintWriter instead of DataOutputStream ▪ Use FileReader instead of FileInputStream ▪ Use BufferedReader instead of DataInputStream
  • 21. File Handling High level text file output: ▪ Set up File object, FileOutputStream object and PrintWriter object. ▪ Use the println() methods to write to the file – can write any primitive data type which is then converted to a String. File myFile = new File("someTextFile.txt"); FileOutputStream outStream = new FileOutputStream(myFile); PrintWriter outPrintStream = new PrintWriter(outStream); outPrintStream.println(99.0); outPrintStream.println("123"); outPrintStream.close();
  • 22. File Handling High level text file input: ▪ Set up File object, FileReader object and BufferedReader object. ▪ Use the readLine() methods to read from the file – everything is read as a String, convert to other type if necessary File myFile = new File("someTextFile.txt"); FileReader inFileReader = new FileReader(myFile); BufferedReader inBufferedReader = new BufferedReader(inFileReader); String line = inBufferedReader.readLine(); inBufferedReader.close();
  • 23. File Handling High level text file input: ▪ We can also use the Scanner class, and associate it directly to a file, instead of associating it with the console ▪ Use Scanner methods to read and automatically convert File myFile = new File("someTextFile.txt"); Scanner scanFile = new Scanner(myFile); String s = scanFile.next(); Double d = scanFile.nextDouble(); Boolean b = scanFile.nextBoolean();
  • 24. File Handling High level text file input/output: File PrintWriter FileOutputStream println() File BufferedRead FileReader readLine() File Scanner next() nextInt() nextFloat()
  • 25. File Handling ▪ What about reading and writing objects? ▪ We can read and write the individual data members using a Data Stream ▪ Better to use ObjectOutputStream and ObjectInputStream objects. ▪ Note: to write an object, we need to add to its class definition: ▪ But we don’t need to do anything else – no compulsory methods to write… class Student implements Serializable
  • 26. File Handling High level object file output: ▪ Set up File object, FileOutputStream object and ObjectOutputStream object. ▪ Write using the writeObject() method: File myFile = new File("someFile.dat"); FileOutputStream outStream = new FileOutputStream(myFile); ObjectOutputStream outObjStream = new ObjectOutputStream(outStream); Student s = new Student(); outObjStream.writeObject(s);
  • 27. File Handling High level object file input: ▪ Set up File object, FileInputStream object and ObjectInputStream object. ▪ Use the readObject methods to read from the file. Note: we need to cast the object to the correct object class. ▪ We can read and write objects from different classes in one file. File myFile = new File("someFile.dat"); FileInputStream inStream = new FileInputStream(myFile); ObjectInputStream inObjectStream = new ObjectInputStream(inStream); Student s; s = (Student) inObjectStream.readObject();
  • 28. File Handling High level - object File ObjectOutputStream FileOutputStream writeObject() File ObjectInputStream FileInputStream readObject()