SlideShare a Scribd company logo
Java/J2EE Programming Training
Simple Java I/O
Page 1Classification: Restricted
Agenda
• Streams
• Using a stream
• Manipulating the input data
• Basics of the LineReader constructor
• The LineWriter class
• Flushing the buffer
• PrintWriter
• About FileDialogs
• Typical FileDialog window
• FileDialog constructors
• Useful FileDialog methods I
• Useful FileDialog methods II
• Serialization
• Conditions for serializability
• Writing objects to a file
Page 2Classification: Restricted
Streams
• All modern I/O is stream-based
• A stream is a connection to a source of data or to a destination for data
(sometimes both)
• An input stream may be associated with the keyboard
• An input stream or an output stream may be associated with a file
• Different streams have different characteristics:
• A file has a definite length, and therefore an end
• Keyboard input has no specific end
Page 3Classification: Restricted
How to do I/O
import java.io.*;
• Open the stream
• Use the stream (read, write, or both)
• Close the stream
Page 4Classification: Restricted
Why Java I/O is hard
• Java I/O is very powerful, with an overwhelming number of options
• Any given kind of I/O is not particularly difficult
• The trick is to find your way through the maze of possibilities
open
use
close
Page 5Classification: Restricted
Opening a stream
• There is data external to your program that you want to get, or you want to
put data somewhere outside your program
• When you open a stream, you are making a connection to that external
place
• Once the connection is made, you forget about the external place and just
use the stream
open
use
close
Page 6Classification: Restricted
Example of opening a stream
• A FileReader is a used to connect to a file that will be used for input:
FileReader fileReader =
new FileReader(fileName);
• The fileName specifies where the (external) file is to be found
• You never use fileName again; instead, you use fileReader
Page 7Classification: Restricted
Using a stream
• Some streams can be used only for input, others only for output, still others
for both
• Using a stream means doing input from it or output to it
• But it’s not usually that simple--you need to manipulate the data in some
way as it comes in or goes out
Page 8Classification: Restricted
Example of using a stream
int ch;
ch = fileReader.read( );
• The fileReader.read() method reads one character and returns it as an
integer, or -1 if there are no more characters to read
• The meaning of the integer depends on the file encoding (ASCII, Unicode,
other)
Page 9Classification: Restricted
Manipulating the input data
• Reading characters as integers isn’t usually what you want to do
• A BufferedReader will convert integers to characters; it can also read whole
lines
• The constructor for BufferedReader takes a FileReader parameter:
BufferedReader bufferedReader =
new BufferedReader(fileReader);
Page 10Classification: Restricted
Reading lines
String s;
s = bufferedReader.readLine( );
• A BufferedReader will return null if there is nothing more to read
Page 11Classification: Restricted
Closing
• A stream is an expensive resource
• There is a limit on the number of streams that you can have open at one
time
• You should not have more than one stream open on the same file
• You must close a stream before you can open it again
• Always close your streams!
Page 12Classification: Restricted
Text files
• Text (.txt) files are the simplest kind of files
• text files can be used by many different programs
• Formatted text files (such as .doc files) also contain binary formatting
information
• Only programs that “know the secret code” can make sense formatted text
files
• Compilers, in general, work only with text
Page 13Classification: Restricted
My LineReader class
class LineReader {
BufferedReader bufferedReader;
LineReader(String fileName) {...}
String readLine( ) {...}
void close( ) {...}
}
Page 14Classification: Restricted
Basics of the LineReader constructor
• Create a FileReader for the named file:
FileReader fileReader =
new FileReader(fileName);
• Use it as input to a BufferedReader:
BufferedReader bufferedReader =
new BufferedReader(fileReader);
• Use the BufferedReader; but first, we need to catch possible Exceptions
Page 15Classification: Restricted
The full LineReader constructor
LineReader(String fileName) {
FileReader fileReader = null;
try { fileReader = new FileReader(fileName); }
catch (FileNotFoundException e) {
System.err.println
("LineReader can't find input file: " + fileName);
e.printStackTrace( );
}
bufferedReader = new BufferedReader(fileReader);
}
Page 16Classification: Restricted
readLine
String readLine( ) {
try {
return bufferedReader.readLine( );
}
catch(IOException e) {
e.printStackTrace( );
}
return null;
}
Page 17Classification: Restricted
close
void close() {
try {
bufferedReader.close( );
}
catch(IOException e) { }
}
Page 18Classification: Restricted
How did I figure that out?
• I wanted to read lines from a file
• I found a readLine method in the BufferedReader class
• The constructor for BufferedReader takes a Reader as an argument
• An InputStreamReader is a kind of Reader
• A FileReader is a kind of InputStreamReader
Page 19Classification: Restricted
The LineWriter class
class LineWriter {
PrintWriter printWriter;
LineWriter(String fileName) {...}
void writeLine(String line) {...}
void close( ) {...}
}
Page 20Classification: Restricted
The constructor for LineWriter
LineWriter(String fileName) {
try {
printWriter =
new PrintWriter(
new FileOutputStream(fileName), true);
}
catch(Exception e) {
System.err.println("LineWriter can't " +
"use output file: " + fileName);
}
}
Page 21Classification: Restricted
Flushing the buffer
• When you put information into a buffered output stream, it goes into a
buffer
• The buffer may not be written out right away
• If your program crashes, you may not know how far it got before it crashed
• Flushing the buffer is forcing the information to be written out
Page 22Classification: Restricted
PrintWriter
• Buffers are automatically flushed when the program ends normally
• Usually it is your responsibility to flush buffers if the program does not end
normally
• PrintWriter can do the flushing for you
public PrintWriter(OutputStream out,
boolean autoFlush)
Page 23Classification: Restricted
writeLine
void writeLine(String line) {
printWriter.println(line);
}
Page 24Classification: Restricted
close
void close( ) {
printWriter.flush( );
try { printWriter.close( ); }
catch(Exception e) { }
}
Page 25Classification: Restricted
About FileDialogs
• The FileDialog class displays a window from which the user can select a file
• The FileDialog window is modal--the application cannot continue until it is
closed
• Only applications, not applets, can use a FileDialog; only applications can
access files
• Every FileDialog window is associated with a Frame
Page 26Classification: Restricted
Typical FileDialog window
Page 27Classification: Restricted
FileDialog constructors
• FileDialog(Frame f)
• Creates a FileDialog attached to Frame f
• FileDialog(Frame f, String title)
• Creates a FileDialog attached to Frame f, with the given title
• FileDialog(Frame f, String title, int type)
• Creates a FileDialog attached to Frame f, with the given title; the type
can be either FileDialog.LOAD or FileDialog.SAVE
Page 28Classification: Restricted
Useful FileDialog methods I
• String getDirectory()
• Returns the selected directory
• String getFile()
• Returns the name of the currently selected file, or null if no file is
selected
• int getMode()
• Returns either FileDialog.LOAD or FileDialog.SAVE, depending on what
the dialog is being used for
Page 29Classification: Restricted
Useful FileDialog methods II
• void setDirectory(String directory)
• Changes the current directory to directory
• void setFile(String fileName)
• Changes the current file to fileName
• void setMode(int mode)
• Sets the mode to either FileDialog.LOAD or FileDialog.SAVE
Page 30Classification: Restricted
Using a FileDialog
• Using a FileDialog isn’t difficult, but it is lengthy
• See my LineReader class (in the Encryption assignment) for a complete
example
Page 31Classification: Restricted
Serialization
• You can also read and write objects to files
• Object I/O goes by the awkward name of serialization
• Serialization in other languages can be very difficult, because objects may
contain references to other objects
• Java makes serialization (almost) easy
Page 32Classification: Restricted
Conditions for serializability
• If an object is to be serialized:
• The class must be declared as public
• The class must implement Serializable
• The class must have a no-argument constructor
• All fields of the class must be serializable: either primitive types or
serializable objects
Page 33Classification: Restricted
Implementing the Serializable interface
•To “implement” an interface means to
define all the methods declared by that
interface, but...
•The Serializable interface does not define
any methods!
•Question: What possible use is there for an
interface that does not declare any methods?
•Answer: Serializable is used as flag to tell Java it
needs to do extra work with this class
Page 34Classification: Restricted
Writing objects to a file
ObjectOutputStream objectOut =
new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(fileName)));
objectOut.writeObject(serializableObject);
objectOut.close( );
Page 35Classification: Restricted
Reading objects from a file
ObjectInputStream objectIn =
new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(fileName)));
myObject = (itsType)objectIn.readObject( );
objectIn.close( );
Page 36Classification: Restricted
What have I left out?
• Encrypted files, compressed files, files sent over internet connections, ...
• Exceptions! All I/O involves Exceptions!
• try { statements involving I/O }
catch (IOException e) {
e.printStackTrace ( );
}
Page 37Classification: Restricted
Thank You

More Related Content

What's hot

Web technology unit I - Part B
Web technology unit I - Part BWeb technology unit I - Part B
Web technology unit I - Part B
SSN College of Engineering, Kalavakkam
 
Flexible Indexing in Lucene 4.0
Flexible Indexing in Lucene 4.0Flexible Indexing in Lucene 4.0
Flexible Indexing in Lucene 4.0
Lucidworks (Archived)
 
Dom parser
Dom parserDom parser
Dom parser
sana mateen
 
Reimagining Serials handout: BIBFRAME Exercise
Reimagining Serials handout: BIBFRAME ExerciseReimagining Serials handout: BIBFRAME Exercise
Reimagining Serials handout: BIBFRAME Exercise
NASIG
 
Xml dom
Xml domXml dom
Xml dom
sana mateen
 
paradise city
paradise cityparadise city
paradise city
Chandrashekar Jinka
 
Avro intro
Avro introAvro intro
Avro intro
Randy Abernethy
 
CenitHub Presentations | 3- Translator
CenitHub Presentations | 3- TranslatorCenitHub Presentations | 3- Translator
CenitHub Presentations | 3- Translator
Miguel Sancho
 
Understanding Character Encodings
Understanding Character EncodingsUnderstanding Character Encodings
Understanding Character Encodings
Mobisoft Infotech
 
Understanding XML DOM
Understanding XML DOMUnderstanding XML DOM
Understanding XML DOM
Om Vikram Thapa
 
Content Registration - Crossref LIVE Hannover
Content Registration - Crossref LIVE HannoverContent Registration - Crossref LIVE Hannover
Content Registration - Crossref LIVE Hannover
Crossref
 
Jstreams
JstreamsJstreams
Experience protocol buffer on android
Experience protocol buffer on androidExperience protocol buffer on android
Experience protocol buffer on android
Richard Chang
 
Xml processors
Xml processorsXml processors
Xml processors
Saurav Mawandia
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web Introduction
Ahmed Swilam
 
Intro. to the internet and web
Intro. to the internet and webIntro. to the internet and web
Intro. to the internet and web
dofirfauzi1302
 
Assets, files, and data parsing
Assets, files, and data parsingAssets, files, and data parsing
Assets, files, and data parsing
Aly Arman
 
Introduction to libre « fulltext » technology
Introduction to libre « fulltext » technologyIntroduction to libre « fulltext » technology
Introduction to libre « fulltext » technology
Robert Viseur
 
XML
XMLXML

What's hot (19)

Web technology unit I - Part B
Web technology unit I - Part BWeb technology unit I - Part B
Web technology unit I - Part B
 
Flexible Indexing in Lucene 4.0
Flexible Indexing in Lucene 4.0Flexible Indexing in Lucene 4.0
Flexible Indexing in Lucene 4.0
 
Dom parser
Dom parserDom parser
Dom parser
 
Reimagining Serials handout: BIBFRAME Exercise
Reimagining Serials handout: BIBFRAME ExerciseReimagining Serials handout: BIBFRAME Exercise
Reimagining Serials handout: BIBFRAME Exercise
 
Xml dom
Xml domXml dom
Xml dom
 
paradise city
paradise cityparadise city
paradise city
 
Avro intro
Avro introAvro intro
Avro intro
 
CenitHub Presentations | 3- Translator
CenitHub Presentations | 3- TranslatorCenitHub Presentations | 3- Translator
CenitHub Presentations | 3- Translator
 
Understanding Character Encodings
Understanding Character EncodingsUnderstanding Character Encodings
Understanding Character Encodings
 
Understanding XML DOM
Understanding XML DOMUnderstanding XML DOM
Understanding XML DOM
 
Content Registration - Crossref LIVE Hannover
Content Registration - Crossref LIVE HannoverContent Registration - Crossref LIVE Hannover
Content Registration - Crossref LIVE Hannover
 
Jstreams
JstreamsJstreams
Jstreams
 
Experience protocol buffer on android
Experience protocol buffer on androidExperience protocol buffer on android
Experience protocol buffer on android
 
Xml processors
Xml processorsXml processors
Xml processors
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web Introduction
 
Intro. to the internet and web
Intro. to the internet and webIntro. to the internet and web
Intro. to the internet and web
 
Assets, files, and data parsing
Assets, files, and data parsingAssets, files, and data parsing
Assets, files, and data parsing
 
Introduction to libre « fulltext » technology
Introduction to libre « fulltext » technologyIntroduction to libre « fulltext » technology
Introduction to libre « fulltext » technology
 
XML
XMLXML
XML
 

Similar to Java I/O

Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
JayasankarPR2
 
32sql server
32sql server32sql server
32sql server
Sireesh K
 
31cs
31cs31cs
31cs
Sireesh K
 
Javaio
JavaioJavaio
Javaio
Jaya Jeswani
 
Javaio
JavaioJavaio
Javaio
Jaya Jeswani
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
PawanMM
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
Hitesh-Java
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
NiharikaDubey17
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
HindAlmisbahi
 
Input & output
Input & outputInput & output
Input & output
SAIFUR RAHMAN
 
Exception Handling ,templates in C++
Exception Handling ,templates in C++Exception Handling ,templates in C++
Exception Handling ,templates in C++
jamilmalik19
 
Binary File.pptx
Binary File.pptxBinary File.pptx
Binary File.pptx
MasterDarsh
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
Gera Paulos
 
ASP.NET Session 7
ASP.NET Session 7ASP.NET Session 7
ASP.NET Session 7
Sisir Ghosh
 
Python Tutorial Part 2
Python Tutorial Part 2Python Tutorial Part 2
Python Tutorial Part 2
Haitham El-Ghareeb
 
C- language Lecture 8
C- language Lecture 8C- language Lecture 8
C- language Lecture 8
Hatem Abd El-Salam
 
Storage 8
Storage   8Storage   8
Storage 8
Michael Shrove
 
Microsoft power point chapter 5 file edited
Microsoft power point   chapter 5 file editedMicrosoft power point   chapter 5 file edited
Microsoft power point chapter 5 file edited
Linga Lgs
 

Similar to Java I/O (20)

Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
32sql server
32sql server32sql server
32sql server
 
31cs
31cs31cs
31cs
 
Javaio
JavaioJavaio
Javaio
 
Javaio
JavaioJavaio
Javaio
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Input & output
Input & outputInput & output
Input & output
 
Exception Handling ,templates in C++
Exception Handling ,templates in C++Exception Handling ,templates in C++
Exception Handling ,templates in C++
 
Binary File.pptx
Binary File.pptxBinary File.pptx
Binary File.pptx
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
 
ASP.NET Session 7
ASP.NET Session 7ASP.NET Session 7
ASP.NET Session 7
 
Python Tutorial Part 2
Python Tutorial Part 2Python Tutorial Part 2
Python Tutorial Part 2
 
C- language Lecture 8
C- language Lecture 8C- language Lecture 8
C- language Lecture 8
 
Storage 8
Storage   8Storage   8
Storage 8
 
Microsoft power point chapter 5 file edited
Microsoft power point   chapter 5 file editedMicrosoft power point   chapter 5 file edited
Microsoft power point chapter 5 file edited
 

More from DeeptiJava

Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
DeeptiJava
 
Java Generics
Java GenericsJava Generics
Java Generics
DeeptiJava
 
Java Collection
Java CollectionJava Collection
Java Collection
DeeptiJava
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
DeeptiJava
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
DeeptiJava
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
DeeptiJava
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
DeeptiJava
 
Java Thread
Java ThreadJava Thread
Java Thread
DeeptiJava
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
DeeptiJava
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
DeeptiJava
 
JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
DeeptiJava
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate Basics
DeeptiJava
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
DeeptiJava
 

More from DeeptiJava (13)

Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Collection
Java CollectionJava Collection
Java Collection
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Java Thread
Java ThreadJava Thread
Java Thread
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
 
JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate Basics
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 

Recently uploaded

Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 

Recently uploaded (20)

Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 

Java I/O

  • 2. Page 1Classification: Restricted Agenda • Streams • Using a stream • Manipulating the input data • Basics of the LineReader constructor • The LineWriter class • Flushing the buffer • PrintWriter • About FileDialogs • Typical FileDialog window • FileDialog constructors • Useful FileDialog methods I • Useful FileDialog methods II • Serialization • Conditions for serializability • Writing objects to a file
  • 3. Page 2Classification: Restricted Streams • All modern I/O is stream-based • A stream is a connection to a source of data or to a destination for data (sometimes both) • An input stream may be associated with the keyboard • An input stream or an output stream may be associated with a file • Different streams have different characteristics: • A file has a definite length, and therefore an end • Keyboard input has no specific end
  • 4. Page 3Classification: Restricted How to do I/O import java.io.*; • Open the stream • Use the stream (read, write, or both) • Close the stream
  • 5. Page 4Classification: Restricted Why Java I/O is hard • Java I/O is very powerful, with an overwhelming number of options • Any given kind of I/O is not particularly difficult • The trick is to find your way through the maze of possibilities open use close
  • 6. Page 5Classification: Restricted Opening a stream • There is data external to your program that you want to get, or you want to put data somewhere outside your program • When you open a stream, you are making a connection to that external place • Once the connection is made, you forget about the external place and just use the stream open use close
  • 7. Page 6Classification: Restricted Example of opening a stream • A FileReader is a used to connect to a file that will be used for input: FileReader fileReader = new FileReader(fileName); • The fileName specifies where the (external) file is to be found • You never use fileName again; instead, you use fileReader
  • 8. Page 7Classification: Restricted Using a stream • Some streams can be used only for input, others only for output, still others for both • Using a stream means doing input from it or output to it • But it’s not usually that simple--you need to manipulate the data in some way as it comes in or goes out
  • 9. Page 8Classification: Restricted Example of using a stream int ch; ch = fileReader.read( ); • The fileReader.read() method reads one character and returns it as an integer, or -1 if there are no more characters to read • The meaning of the integer depends on the file encoding (ASCII, Unicode, other)
  • 10. Page 9Classification: Restricted Manipulating the input data • Reading characters as integers isn’t usually what you want to do • A BufferedReader will convert integers to characters; it can also read whole lines • The constructor for BufferedReader takes a FileReader parameter: BufferedReader bufferedReader = new BufferedReader(fileReader);
  • 11. Page 10Classification: Restricted Reading lines String s; s = bufferedReader.readLine( ); • A BufferedReader will return null if there is nothing more to read
  • 12. Page 11Classification: Restricted Closing • A stream is an expensive resource • There is a limit on the number of streams that you can have open at one time • You should not have more than one stream open on the same file • You must close a stream before you can open it again • Always close your streams!
  • 13. Page 12Classification: Restricted Text files • Text (.txt) files are the simplest kind of files • text files can be used by many different programs • Formatted text files (such as .doc files) also contain binary formatting information • Only programs that “know the secret code” can make sense formatted text files • Compilers, in general, work only with text
  • 14. Page 13Classification: Restricted My LineReader class class LineReader { BufferedReader bufferedReader; LineReader(String fileName) {...} String readLine( ) {...} void close( ) {...} }
  • 15. Page 14Classification: Restricted Basics of the LineReader constructor • Create a FileReader for the named file: FileReader fileReader = new FileReader(fileName); • Use it as input to a BufferedReader: BufferedReader bufferedReader = new BufferedReader(fileReader); • Use the BufferedReader; but first, we need to catch possible Exceptions
  • 16. Page 15Classification: Restricted The full LineReader constructor LineReader(String fileName) { FileReader fileReader = null; try { fileReader = new FileReader(fileName); } catch (FileNotFoundException e) { System.err.println ("LineReader can't find input file: " + fileName); e.printStackTrace( ); } bufferedReader = new BufferedReader(fileReader); }
  • 17. Page 16Classification: Restricted readLine String readLine( ) { try { return bufferedReader.readLine( ); } catch(IOException e) { e.printStackTrace( ); } return null; }
  • 18. Page 17Classification: Restricted close void close() { try { bufferedReader.close( ); } catch(IOException e) { } }
  • 19. Page 18Classification: Restricted How did I figure that out? • I wanted to read lines from a file • I found a readLine method in the BufferedReader class • The constructor for BufferedReader takes a Reader as an argument • An InputStreamReader is a kind of Reader • A FileReader is a kind of InputStreamReader
  • 20. Page 19Classification: Restricted The LineWriter class class LineWriter { PrintWriter printWriter; LineWriter(String fileName) {...} void writeLine(String line) {...} void close( ) {...} }
  • 21. Page 20Classification: Restricted The constructor for LineWriter LineWriter(String fileName) { try { printWriter = new PrintWriter( new FileOutputStream(fileName), true); } catch(Exception e) { System.err.println("LineWriter can't " + "use output file: " + fileName); } }
  • 22. Page 21Classification: Restricted Flushing the buffer • When you put information into a buffered output stream, it goes into a buffer • The buffer may not be written out right away • If your program crashes, you may not know how far it got before it crashed • Flushing the buffer is forcing the information to be written out
  • 23. Page 22Classification: Restricted PrintWriter • Buffers are automatically flushed when the program ends normally • Usually it is your responsibility to flush buffers if the program does not end normally • PrintWriter can do the flushing for you public PrintWriter(OutputStream out, boolean autoFlush)
  • 24. Page 23Classification: Restricted writeLine void writeLine(String line) { printWriter.println(line); }
  • 25. Page 24Classification: Restricted close void close( ) { printWriter.flush( ); try { printWriter.close( ); } catch(Exception e) { } }
  • 26. Page 25Classification: Restricted About FileDialogs • The FileDialog class displays a window from which the user can select a file • The FileDialog window is modal--the application cannot continue until it is closed • Only applications, not applets, can use a FileDialog; only applications can access files • Every FileDialog window is associated with a Frame
  • 28. Page 27Classification: Restricted FileDialog constructors • FileDialog(Frame f) • Creates a FileDialog attached to Frame f • FileDialog(Frame f, String title) • Creates a FileDialog attached to Frame f, with the given title • FileDialog(Frame f, String title, int type) • Creates a FileDialog attached to Frame f, with the given title; the type can be either FileDialog.LOAD or FileDialog.SAVE
  • 29. Page 28Classification: Restricted Useful FileDialog methods I • String getDirectory() • Returns the selected directory • String getFile() • Returns the name of the currently selected file, or null if no file is selected • int getMode() • Returns either FileDialog.LOAD or FileDialog.SAVE, depending on what the dialog is being used for
  • 30. Page 29Classification: Restricted Useful FileDialog methods II • void setDirectory(String directory) • Changes the current directory to directory • void setFile(String fileName) • Changes the current file to fileName • void setMode(int mode) • Sets the mode to either FileDialog.LOAD or FileDialog.SAVE
  • 31. Page 30Classification: Restricted Using a FileDialog • Using a FileDialog isn’t difficult, but it is lengthy • See my LineReader class (in the Encryption assignment) for a complete example
  • 32. Page 31Classification: Restricted Serialization • You can also read and write objects to files • Object I/O goes by the awkward name of serialization • Serialization in other languages can be very difficult, because objects may contain references to other objects • Java makes serialization (almost) easy
  • 33. Page 32Classification: Restricted Conditions for serializability • If an object is to be serialized: • The class must be declared as public • The class must implement Serializable • The class must have a no-argument constructor • All fields of the class must be serializable: either primitive types or serializable objects
  • 34. Page 33Classification: Restricted Implementing the Serializable interface •To “implement” an interface means to define all the methods declared by that interface, but... •The Serializable interface does not define any methods! •Question: What possible use is there for an interface that does not declare any methods? •Answer: Serializable is used as flag to tell Java it needs to do extra work with this class
  • 35. Page 34Classification: Restricted Writing objects to a file ObjectOutputStream objectOut = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream(fileName))); objectOut.writeObject(serializableObject); objectOut.close( );
  • 36. Page 35Classification: Restricted Reading objects from a file ObjectInputStream objectIn = new ObjectInputStream( new BufferedInputStream( new FileInputStream(fileName))); myObject = (itsType)objectIn.readObject( ); objectIn.close( );
  • 37. Page 36Classification: Restricted What have I left out? • Encrypted files, compressed files, files sent over internet connections, ... • Exceptions! All I/O involves Exceptions! • try { statements involving I/O } catch (IOException e) { e.printStackTrace ( ); }