SlideShare a Scribd company logo
1 of 32
2016 Winter
LAB #6
Prepared by: Berk Soysal
Java's IO package mostly concerns itself with the reading of
raw data from a source and writing of raw data to a
destination. The most typical sources and destinations of
data are these:
• Files
• Pipes
• Network Connections
• In-memory Buffers (e.g. arrays)
• System.in, System.out, System.error
2016 Winter
• IO Streams are a core concept in Java IO. A stream is a
conceptually endless flow of data.
• You can either read from a stream or write to a stream. A
stream is connected to a data source or a data
destination.
• Streams in Java IO can be either byte based (reading and
writing bytes) or character based (reading and writing
characters).
2016 Winter
• A program that needs to read data from some source
needs an InputStream or a Reader. A program that needs
to write data to some destination needs an OutputStream
or a Writer.
• InputStream
• OutputStream
• Reader
• Writer
}
}Character
Streams
Byte
Streams
2016 Winter
• Byte streams are associated with data-based (binary) I/O.
Examples of binary data include image and audio files, jpeg
and mp3 files for example.
•
• In Java, characters are encoded with Unicodes — character
streams are associated with text-based (human readable)
I/O. The character streams are called readers and writers as
I mentioned before.
• Java Character streams are used to perform input and
output for 16-bit unicode.
Folder Lab6 Lab6 Examples  01  Unicode.java
Java Byte streams are used to perform input and output
of 8-bit bytes.
2016 Winter
• You can get random access to files with Java IO via the
RandomAccessFile Class.
• Random access doesn't mean that you read or write from
truly random places. It just means that you can skip around
the file and read from or write to it at the same time in any
way you want. No particular access sequence is enforced.
• This makes it possible to overwrite parts of an existing file,
to append to it, delete from it, and of course read from the
file from wherever you need to read from it.
2016 Winter
• You can get random access to files with Java IO via the
RandomAccessFile Class.
• Random access doesn't mean that you read or write from
truly random places. It just means that you can skip around
the file and read from or write to it at the same time in any
way you want. No particular access sequence is enforced.
• This makes it possible to overwrite parts of an existing file,
to append to it, delete from it, and of course read from the
file from wherever you need to read from it.
2016 Winter
InputStream and OutputStream are two abstract classes that define the
methods that are common to all input and output streams.
The class InputStream declares the following three methods.
• int read(): Reads the next byte of data from the input stream. If no
byte is available, because the end of the stream has been reached, the
value −1 is returned;
• int read( byte[] b ): Reads some number of bytes from the input
stream and stores them into the buffer array b. The number of bytes actually
read is returned as an integer;
• close(): Closes this input stream and releases any system resources
associated with the stream.
Since InputStream is an abstract class it is never instantiated.
2016 Winter
The class OutputStream declares the following three methods.
• write(byte[] b): Writes b.length bytes from the specified byte array
to this output stream;
• flush(): Flushes this output stream and forces any buffered output
bytes to be written out;
• close(): Closes this output stream and releases any system resources
associated with the stream.
2016 Winter
2016 Winter
Two objects are predefined and readily available for your
programs. System.in is an input stream associated with the
keyboard, and System.out is an output stream associated with
the console.
Remember ?
System.out.println(“Hello World”)
-----------------------------------
Scanner in = new Scanner(System.in);
String name = in.nextLine();
2016 Winter
Usually we follow 3 steps to write a file:
 Opening a file.
 Writing to that file.
 Closing the file.
 Closing the file is especially important since if the file
remains open, the internal and external resources remain
unavailable for other files.
2016 Winter
Reading from a file involves creating a FileInputStream object.
We’ll consider two constructors.
FileInputStream( String name ): This constructor receives the
name of the file as an argument. Example,
InputStream in = new FileInputStream( "data.txt" );
FileInputStream( File file ): This constructor receives a File
object as an argument, which is the representation of an
external file.
File f = new File( "data.txt" );
InputStream in = new FileInputStream( f );
2016 Winter
Because a FileInputStream allows to read bytes only, Java defines an
InputStreamReader as bridge from byte to character streams. Its usage is
as follows.
InputStreamReader in = new InputStreamReader(new
FileInputStream( "data.txt" ));
or
InputStreamReader in = new InputStreamReader( System.in );
• int read(): Reads a single character. Returns −1 if the end of stream has
been reached. The return type is int, the value −1 indicates the end-of-file
(eof). The value must be interpreted as a character, i.e. must be converted,
int i = in.read();
if ( i != -1 ) {
char c = (char) i;
}
Folder  Lab6 Lab6 Examples  02  Keyboard.java
2016 Winter
• int read( char [] b ): Reads characters into an array. Returns the number
of characters read, or −1 if the end of the stream has been reached.
InputStreamReader in = new InputStreamReader(new
FileInputStream( "data.txt" ));
char[] buffer = new char[ 256 ];
num = in.read( buffer );
String str = new String( buffer );
2016 Winter
Write a class named Exercise1 that reads characters from
the keyboard using the method read( char[] b );
The maximum number of characters that can be read at a
time is fixed and determined by the size of the buffer.
Use the class Keyboard from the above example as a
starting point.
2016 Winter
For some applications, the input should be read one line at a
time. For this, you will be using an object of the class
BufferedReader.
A BufferedReader uses an InputStreamReader to read the
content.
The InputStreamReader uses an InputStream to read the raw
data. Each layer (object) adds new functionalities.
 The InputStream reads the data (bytes).
 The InputStreamReader converts the bytes to characters.
 Finally, the BufferedReader regroups the characters into
groups, here lines.
2016 Winter
FileInputStream f = FileInputStream( "data.txt" );
InputStreamReader is = new InputStreamReader( f );
BufferedReader in = new BufferedReader( is );
or in short form;
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream("data.txt") ) );
String s = in.readLine();
Folder Lab6 Lab6 Examples  03  Copy.java
2016 Winter
Write a class named Exercise2 that prints all the lines that
contain a certain word.
For each line containing the word, print the line number
followed by the line itself.
2016 Winter
Write a class named Exercise3 that counts the number of
occurrences of a given word within a file.
2016 Winter
Write a class Exercise4 that fetches the content of a Web
page and prints it on the console.
2016 Winter
There are two useful File utility methods, which can be used to create
directories:
mkdir( ) method creates a directory, returning true on success and false on
failure. Failure indicates that the path specified in the File object already
exists, or that the directory cannot be created because the entire path does
not exist yet.
mkdirs() method creates both a directory and all the parents of the
directory.
import java.io.File;
public class CreateDir {
public static void main(String[] args) {
String dirname = "/tmp/user/java/bin";
File f = new File(dirname);
f.mkdirs(); // Create directory
}
}
2016 Winter
Writing to a file involves creating a FileOutputStream object.
We’ll consider two constructors.
FileOutputStream( String name ): Creates an output file
stream to write to the file with the specified name.
OutputStream out = new FileOutputStream( "data.txt" );
FileOutputStream( File file ): This constructor receives a File
object as an argument, which is the representation of an
external file.
File f = new File( "data.txt" );
OutputStream out = new FileOutputStream( f );
2016 Winter
Because a FileOutputStream allows to write bytes only, Java defines an
OutputStreamWriter as bridge from byte to character streams. Its usage is
as follows.
OutputStreamWriter out = new OutputStreamWriter (new
FileOutputStream( "data.txt" ));
or
OutputStreamWriter out = new OutputStreamWriter( System.out );
• write( int c ): Writes a single character.
• write( char[] buffer ): Writes an array of characters.
• write( String s ): Writes a String.
2016 Winter
Modify the class Copy.java so that it has a second argument
that will be the name of a destination file. An accordingly,
write a copy of the input to the output file.
2016 Winter
An exception (or exceptional event) is a problem that arises during the
execution of a program. When an Exception occurs the normal flow of the
program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore these exceptions are to be handled.
If a method does not handle a checked exception, the method must declare
it using the throws keyword. The throws keyword appears at the end of a
method's signature.
Catching Exceptions:
A method catches an exception using a combination of the try and catch
keywords. A try/catch block is placed around the code that might generate
an exception. Code within a try/catch block is referred to as protected code,
and the syntax for using try/catch looks like the following:
2016 Winter
try {
//Protected code
} catch(ExceptionType1 e1) {
//Catch block 1
} catch(ExceptionType2 e2) {
//Catch block 2
}
The code which is prone to exceptions is placed in the try block, when an
exception occurs, that exception occurred is handled by catch block
associated with it. Every try block should be immediately followed either
by a catch block or finally block.
The finally block
The finally block follows a try block or a catch block. A finally block of
code always executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that
you want to execute, no matter what happens in the protected code.
2016 Winter
public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
2016 Winter
IOException
“Signals that an I/O exception of some sort has occurred. This
class is the general class of exceptions produced by failed or
interrupted I/O operations.” This is a direct subclass of
Exception, this is therefore a checked exception that must be
handled, caught by a catch clause or declared.
FileNotFoundException
The constructor FileInputStream( String name ) throws an
exception of type FileNotFoundException, which is a direct
subclass of IOException. This exception must be handled, i.e.
caught by a catch clause or declared.
2016 Winter
Again here, the solution proposed by Java is more complex than with most
other programming languages.
java.text.Format
Format is the abstract superclass of all the formatting classes, namely
DateFormat and NumberFormat. The following occurs when printing a
floating point number.
public class Test {
public static void main( String[] args ) {
System.out.println( Math.PI );
}
}
2016 Winter
Sometimes this what you want and sometimes not (e.g. printing dollar
amounts). In order to print only a fixed number of decimals, one needs to
create a NumberFormat instance and tell this instance how to format
numbers.
First, the NumberFormat class is not imported by default, therefore you will
have to import it into your program.
Next, you will create and instance and then use the instance methods
setMaximumFractionDigits and setMinimumFractionDigits to set the
number of digits for the fractional part to 2.
Finally, you can use the instance method format, of the number format
object, to create the string representations.
Folder  Lab6 Lab6 Examples  04  Test.java
Folder  Lab6 Lab6 Examples  04  Test2.java
2016 Winter
2016 Winter

More Related Content

What's hot

Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in JavaErhan Bagdemir
 
Adobe Flash Actionscript language basics chapter-2
Adobe Flash Actionscript language basics chapter-2Adobe Flash Actionscript language basics chapter-2
Adobe Flash Actionscript language basics chapter-2Nafis Ahmed
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java langer4711
 
introduction to c #
introduction to c #introduction to c #
introduction to c #Sireesh K
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
Knolx Session: Introducing Extractors in Scala
Knolx Session: Introducing Extractors in ScalaKnolx Session: Introducing Extractors in Scala
Knolx Session: Introducing Extractors in ScalaAyush Mishra
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaAyush Mishra
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structuresagorolabs
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in ScalaAyush Mishra
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaRahul Jain
 

What's hot (20)

Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Simplicitly
SimplicitlySimplicitly
Simplicitly
 
Adobe Flash Actionscript language basics chapter-2
Adobe Flash Actionscript language basics chapter-2Adobe Flash Actionscript language basics chapter-2
Adobe Flash Actionscript language basics chapter-2
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
 
introduction to c #
introduction to c #introduction to c #
introduction to c #
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Chapter 16
Chapter 16Chapter 16
Chapter 16
 
Knolx Session: Introducing Extractors in Scala
Knolx Session: Introducing Extractors in ScalaKnolx Session: Introducing Extractors in Scala
Knolx Session: Introducing Extractors in Scala
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
 
PCSTt11 overview of java
PCSTt11 overview of javaPCSTt11 overview of java
PCSTt11 overview of java
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
#_ varible function
#_ varible function #_ varible function
#_ varible function
 
Variable
VariableVariable
Variable
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
C#
C#C#
C#
 

Similar to Java Tutorial Lab 6

UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesSakkaravarthiS1
 
L21 io streams
L21 io streamsL21 io streams
L21 io streamsteach4uin
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptxRathanMB
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptxssuser9d7049
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptxcherryreddygannu
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Outputphanleson
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfVithalReddy3
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OWebStackAcademy
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxnoonoboom
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdfSudhanshiBakre1
 

Similar to Java Tutorial Lab 6 (20)

Java I/O
Java I/OJava I/O
Java I/O
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf Notes
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Java stream
Java streamJava stream
Java stream
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
 
Io streams
Io streamsIo streams
Io streams
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 

Recently uploaded

Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 

Recently uploaded (20)

Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 

Java Tutorial Lab 6

  • 1. 2016 Winter LAB #6 Prepared by: Berk Soysal
  • 2. Java's IO package mostly concerns itself with the reading of raw data from a source and writing of raw data to a destination. The most typical sources and destinations of data are these: • Files • Pipes • Network Connections • In-memory Buffers (e.g. arrays) • System.in, System.out, System.error 2016 Winter
  • 3. • IO Streams are a core concept in Java IO. A stream is a conceptually endless flow of data. • You can either read from a stream or write to a stream. A stream is connected to a data source or a data destination. • Streams in Java IO can be either byte based (reading and writing bytes) or character based (reading and writing characters). 2016 Winter
  • 4. • A program that needs to read data from some source needs an InputStream or a Reader. A program that needs to write data to some destination needs an OutputStream or a Writer. • InputStream • OutputStream • Reader • Writer } }Character Streams Byte Streams 2016 Winter
  • 5. • Byte streams are associated with data-based (binary) I/O. Examples of binary data include image and audio files, jpeg and mp3 files for example. • • In Java, characters are encoded with Unicodes — character streams are associated with text-based (human readable) I/O. The character streams are called readers and writers as I mentioned before. • Java Character streams are used to perform input and output for 16-bit unicode. Folder Lab6 Lab6 Examples  01  Unicode.java Java Byte streams are used to perform input and output of 8-bit bytes. 2016 Winter
  • 6. • You can get random access to files with Java IO via the RandomAccessFile Class. • Random access doesn't mean that you read or write from truly random places. It just means that you can skip around the file and read from or write to it at the same time in any way you want. No particular access sequence is enforced. • This makes it possible to overwrite parts of an existing file, to append to it, delete from it, and of course read from the file from wherever you need to read from it. 2016 Winter
  • 7. • You can get random access to files with Java IO via the RandomAccessFile Class. • Random access doesn't mean that you read or write from truly random places. It just means that you can skip around the file and read from or write to it at the same time in any way you want. No particular access sequence is enforced. • This makes it possible to overwrite parts of an existing file, to append to it, delete from it, and of course read from the file from wherever you need to read from it. 2016 Winter
  • 8. InputStream and OutputStream are two abstract classes that define the methods that are common to all input and output streams. The class InputStream declares the following three methods. • int read(): Reads the next byte of data from the input stream. If no byte is available, because the end of the stream has been reached, the value −1 is returned; • int read( byte[] b ): Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer; • close(): Closes this input stream and releases any system resources associated with the stream. Since InputStream is an abstract class it is never instantiated. 2016 Winter
  • 9. The class OutputStream declares the following three methods. • write(byte[] b): Writes b.length bytes from the specified byte array to this output stream; • flush(): Flushes this output stream and forces any buffered output bytes to be written out; • close(): Closes this output stream and releases any system resources associated with the stream. 2016 Winter
  • 11. Two objects are predefined and readily available for your programs. System.in is an input stream associated with the keyboard, and System.out is an output stream associated with the console. Remember ? System.out.println(“Hello World”) ----------------------------------- Scanner in = new Scanner(System.in); String name = in.nextLine(); 2016 Winter
  • 12. Usually we follow 3 steps to write a file:  Opening a file.  Writing to that file.  Closing the file.  Closing the file is especially important since if the file remains open, the internal and external resources remain unavailable for other files. 2016 Winter
  • 13. Reading from a file involves creating a FileInputStream object. We’ll consider two constructors. FileInputStream( String name ): This constructor receives the name of the file as an argument. Example, InputStream in = new FileInputStream( "data.txt" ); FileInputStream( File file ): This constructor receives a File object as an argument, which is the representation of an external file. File f = new File( "data.txt" ); InputStream in = new FileInputStream( f ); 2016 Winter
  • 14. Because a FileInputStream allows to read bytes only, Java defines an InputStreamReader as bridge from byte to character streams. Its usage is as follows. InputStreamReader in = new InputStreamReader(new FileInputStream( "data.txt" )); or InputStreamReader in = new InputStreamReader( System.in ); • int read(): Reads a single character. Returns −1 if the end of stream has been reached. The return type is int, the value −1 indicates the end-of-file (eof). The value must be interpreted as a character, i.e. must be converted, int i = in.read(); if ( i != -1 ) { char c = (char) i; } Folder  Lab6 Lab6 Examples  02  Keyboard.java 2016 Winter
  • 15. • int read( char [] b ): Reads characters into an array. Returns the number of characters read, or −1 if the end of the stream has been reached. InputStreamReader in = new InputStreamReader(new FileInputStream( "data.txt" )); char[] buffer = new char[ 256 ]; num = in.read( buffer ); String str = new String( buffer ); 2016 Winter
  • 16. Write a class named Exercise1 that reads characters from the keyboard using the method read( char[] b ); The maximum number of characters that can be read at a time is fixed and determined by the size of the buffer. Use the class Keyboard from the above example as a starting point. 2016 Winter
  • 17. For some applications, the input should be read one line at a time. For this, you will be using an object of the class BufferedReader. A BufferedReader uses an InputStreamReader to read the content. The InputStreamReader uses an InputStream to read the raw data. Each layer (object) adds new functionalities.  The InputStream reads the data (bytes).  The InputStreamReader converts the bytes to characters.  Finally, the BufferedReader regroups the characters into groups, here lines. 2016 Winter
  • 18. FileInputStream f = FileInputStream( "data.txt" ); InputStreamReader is = new InputStreamReader( f ); BufferedReader in = new BufferedReader( is ); or in short form; BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream("data.txt") ) ); String s = in.readLine(); Folder Lab6 Lab6 Examples  03  Copy.java 2016 Winter
  • 19. Write a class named Exercise2 that prints all the lines that contain a certain word. For each line containing the word, print the line number followed by the line itself. 2016 Winter
  • 20. Write a class named Exercise3 that counts the number of occurrences of a given word within a file. 2016 Winter
  • 21. Write a class Exercise4 that fetches the content of a Web page and prints it on the console. 2016 Winter
  • 22. There are two useful File utility methods, which can be used to create directories: mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet. mkdirs() method creates both a directory and all the parents of the directory. import java.io.File; public class CreateDir { public static void main(String[] args) { String dirname = "/tmp/user/java/bin"; File f = new File(dirname); f.mkdirs(); // Create directory } } 2016 Winter
  • 23. Writing to a file involves creating a FileOutputStream object. We’ll consider two constructors. FileOutputStream( String name ): Creates an output file stream to write to the file with the specified name. OutputStream out = new FileOutputStream( "data.txt" ); FileOutputStream( File file ): This constructor receives a File object as an argument, which is the representation of an external file. File f = new File( "data.txt" ); OutputStream out = new FileOutputStream( f ); 2016 Winter
  • 24. Because a FileOutputStream allows to write bytes only, Java defines an OutputStreamWriter as bridge from byte to character streams. Its usage is as follows. OutputStreamWriter out = new OutputStreamWriter (new FileOutputStream( "data.txt" )); or OutputStreamWriter out = new OutputStreamWriter( System.out ); • write( int c ): Writes a single character. • write( char[] buffer ): Writes an array of characters. • write( String s ): Writes a String. 2016 Winter
  • 25. Modify the class Copy.java so that it has a second argument that will be the name of a destination file. An accordingly, write a copy of the input to the output file. 2016 Winter
  • 26. An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore these exceptions are to be handled. If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. Catching Exceptions: A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following: 2016 Winter
  • 27. try { //Protected code } catch(ExceptionType1 e1) { //Catch block 1 } catch(ExceptionType2 e2) { //Catch block 2 } The code which is prone to exceptions is placed in the try block, when an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block. The finally block The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. 2016 Winter
  • 28. public class ExcepTest{ public static void main(String args[]){ int a[] = new int[2]; try{ System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } finally{ a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } } 2016 Winter
  • 29. IOException “Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.” This is a direct subclass of Exception, this is therefore a checked exception that must be handled, caught by a catch clause or declared. FileNotFoundException The constructor FileInputStream( String name ) throws an exception of type FileNotFoundException, which is a direct subclass of IOException. This exception must be handled, i.e. caught by a catch clause or declared. 2016 Winter
  • 30. Again here, the solution proposed by Java is more complex than with most other programming languages. java.text.Format Format is the abstract superclass of all the formatting classes, namely DateFormat and NumberFormat. The following occurs when printing a floating point number. public class Test { public static void main( String[] args ) { System.out.println( Math.PI ); } } 2016 Winter
  • 31. Sometimes this what you want and sometimes not (e.g. printing dollar amounts). In order to print only a fixed number of decimals, one needs to create a NumberFormat instance and tell this instance how to format numbers. First, the NumberFormat class is not imported by default, therefore you will have to import it into your program. Next, you will create and instance and then use the instance methods setMaximumFractionDigits and setMinimumFractionDigits to set the number of digits for the fractional part to 2. Finally, you can use the instance method format, of the number format object, to create the string representations. Folder  Lab6 Lab6 Examples  04  Test.java Folder  Lab6 Lab6 Examples  04  Test2.java 2016 Winter