SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
Erhan Bagdemir
 
Simplicitly
SimplicitlySimplicitly
Simplicitly
Martin Odersky
 
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
Nafis Ahmed
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
Tobias Coetzee
 
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 Implicit
Martin Odersky
 
Chapter 16
Chapter 16Chapter 16
Chapter 16
Graham Royce
 
Knolx Session: Introducing Extractors in Scala
Knolx Session: Introducing Extractors in ScalaKnolx Session: Introducing Extractors in Scala
Knolx Session: Introducing Extractors in Scala
Ayush Mishra
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Hyderabad Scalability Meetup
 
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
Ayush Mishra
 
PCSTt11 overview of java
PCSTt11 overview of javaPCSTt11 overview of java
PCSTt11 overview of java
Archana Gopinath
 
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
agorolabs
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
Ayush Mishra
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
Martin Odersky
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
Martin Odersky
 
#_ varible function
#_ varible function #_ varible function
#_ varible function
abdullah al mahamud rosi
 
Variable
VariableVariable
Variable
abdullah al mahamud rosi
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Rahul Jain
 
C#
C#C#
C#
Sudhriti Gupta
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
Erhan 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-2
Nafis 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 Implicit
Martin Odersky
 
Knolx Session: Introducing Extractors in Scala
Knolx Session: Introducing Extractors in ScalaKnolx Session: Introducing Extractors in Scala
Knolx Session: Introducing Extractors in Scala
Ayush 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 Scala
Ayush 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 structures
agorolabs
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
Ayush Mishra
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
Martin Odersky
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Rahul Jain
 

Similar to Java Tutorial Lab 6 (20)

Java development development Files lectur6.ppt
Java development development Files lectur6.pptJava development development Files lectur6.ppt
Java development development Files lectur6.ppt
rafeakrafeak
 
Java I/O
Java I/OJava I/O
Java I/O
Jayant Dalvi
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
HindAlmisbahi
 
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
SakkaravarthiS1
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
siragezeynu
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
cs19club
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
GayathriRHICETCSESTA
 
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
RathanMB
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
Ravi Chythanya
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
ssuser9d7049
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
cherryreddygannu
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to StreamsJava IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
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
phanleson
 
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
hungvidien123
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
uthayashangar1
 
Java stream
Java streamJava stream
Java stream
Arati Gadgil
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
People Strategists
 
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
WebStackAcademy
 
Java development development Files lectur6.ppt
Java development development Files lectur6.pptJava development development Files lectur6.ppt
Java development development Files lectur6.ppt
rafeakrafeak
 
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
SakkaravarthiS1
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
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
RathanMB
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
ssuser9d7049
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
cherryreddygannu
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to StreamsJava IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
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
phanleson
 
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
hungvidien123
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
uthayashangar1
 
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
WebStackAcademy
 
Ad

Recently uploaded (20)

Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Top 10 Data Cleansing Tools for 2025.pdf
Top 10 Data Cleansing Tools for 2025.pdfTop 10 Data Cleansing Tools for 2025.pdf
Top 10 Data Cleansing Tools for 2025.pdf
AffinityCore
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Foundation Models for Time Series : A Survey
Foundation Models for Time Series : A SurveyFoundation Models for Time Series : A Survey
Foundation Models for Time Series : A Survey
jayanthkalyanam1
 
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
Imma Valls Bernaus
 
Creating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdfCreating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdf
Applitools
 
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game DevelopmentBest Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Juego Studios
 
Cryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptxCryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptx
riyageorge2024
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Microsoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptxMicrosoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptx
Mekonnen
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025
fs4635986
 
Odoo ERP for Education Management to Streamline Your Education Process
Odoo ERP for Education Management to Streamline Your Education ProcessOdoo ERP for Education Management to Streamline Your Education Process
Odoo ERP for Education Management to Streamline Your Education Process
iVenture Team LLP
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Top 10 Data Cleansing Tools for 2025.pdf
Top 10 Data Cleansing Tools for 2025.pdfTop 10 Data Cleansing Tools for 2025.pdf
Top 10 Data Cleansing Tools for 2025.pdf
AffinityCore
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Foundation Models for Time Series : A Survey
Foundation Models for Time Series : A SurveyFoundation Models for Time Series : A Survey
Foundation Models for Time Series : A Survey
jayanthkalyanam1
 
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
🌱 Green Grafana 🌱 Essentials_ Data, Visualizations and Plugins.pdf
Imma Valls Bernaus
 
Creating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdfCreating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdf
Applitools
 
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game DevelopmentBest Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Juego Studios
 
Cryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptxCryptocurrency Exchange Script like Binance.pptx
Cryptocurrency Exchange Script like Binance.pptx
riyageorge2024
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Microsoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptxMicrosoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptx
Mekonnen
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025Apple Logic Pro X Crack FRESH Version 2025
Apple Logic Pro X Crack FRESH Version 2025
fs4635986
 
Odoo ERP for Education Management to Streamline Your Education Process
Odoo ERP for Education Management to Streamline Your Education ProcessOdoo ERP for Education Management to Streamline Your Education Process
Odoo ERP for Education Management to Streamline Your Education Process
iVenture Team LLP
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
Ad

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