SlideShare a Scribd company logo
File I/O in Java
2
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
• Three stream objects are automatically created for
every application: System.in, System.out, and
System.err.
Types of Streams
• There are 2 kinds of streams
(1)byte streams, (2) character streams
• Java programs perform I/O through streams. A stream is either a
source of or a destination for bytes
• Java implements streams with in class hierarchies defined in the
java.io package.
– InputStream Methods:
– int read( ); returns an int,
int read(byte[ ]); read into byte array and return the number of
bytes read
int read(byte[ ], int, int); The two int arguments in the third
method indicate a sub range in the target array that needs to be
filled.
• void close( ) : When you have finished with a stream, close it
OutputStream Methods:
void write(int)
void write (byte[ ])
void write(byte [ ], int, int)
These methods write to the output stream
void close( ): You should close output streams when you
have finished with them.
void flush( ): Sometimes an output stream accumulates
writes before committing them. The flush ( ) method
allows you to force writes.
Basic Stream Classes:
• Several stream classes are defined in the java.io package
• Fig. below illustrates the hierarchy of some of the
classes in that package
6
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
FileInputStream and FileOutputStream:
• These classes are node streams and, as the name
suggests, they use disk files. The constructors for
these classes allow you to specify the path of the
file to which they are connected. To construct a
FileInputStream, the associated file must exist and
be readable. If you construct a FileOutputStream,
the output file is overwritten if it already exists.
FileInputStream infile = new FileInputStream("myfile.dat");
FileOutputStream outfile = new FileOutputStream(" results.dat");
BufferedInputStream and
BufferedOutputStream:
• These are filter streams that should be used to increase the
efficiency of I/O operations.
• Basic Stream Classes:
DataInputStream and DataOutputStream
These filter streams allow reading and writing of Java
primitive types and some special formats using streams. A
number of methods are provided for the different primitives.
For example:
• DataInputStream Methods:
byte readByte ( )
long readLong ( )
double readDouble ( )
DataOutputStream Methods:
void writeByte (byte)
void writeLong(long)
void writeDouble (double)
Notice that the methods of DataInputStream are paired with the methods
of DataOutputStream.
These streams have methods for reading and writing strings.
Reading Console Input:
In Java, console input is accomplished by reading from System.in. To
obtain a character-based stream that is attached to the console, you
wrap System.in in a BufferedReader object, to create a character
stream. BuffereredReader supports a buffered input stream. Its most
commonly used constructor is shown here:
BufferedReader(Reader inputReader)< br>
Reading Console Input:
• BufferedReader(Reader inputReader)< br>
• Here, inputReader is the stream that is linked to
the instance of BufferedReader that being created.
Reader is an abstract class. One of its concrete
subclasses is InputStreamReader, which converts
bytes to characters. To obtain an
InputStreamReader object that is linked to
System.in, use the following constructor:
InputStreamReader(InputStream inputStream )
Reading Console Input:
• Because System.in refers to an object of type InputStream,
it can be used for inputStream. Putting it all together, the
following line of code creates a BufferedReader that is
connected to the keyboard:
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
• After this statement executes, br is a character-based
stream that is linked to the console through System.in.
• To read a character from a BufferedReader, use read( ).
The version of read( ) that will be using is
• int read( ) throws IOException
BufferedReader to read characters from the
console.
// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
char c;
BufferedReader br = new BufferedReader(new
InputStreamReader (System.in ));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do { c = (char) br.read( );
System.out.println( c);
} while(c ! = 'q');
}
}
Output :
Enter
Characters,
'q' to quit
Helloq
H
e
l
l
o
q
Read a string from console using a
BufferedReader
// Read a string from console using a BufferedReader.
import java.io.*;
class BRReadLines {
public static void main(String args[]) throws IOException{
// Create a BufferReader using System.in
BufferReader br = new BufferReader
(new InputStreamReader(System.in));
String str;
System.out.println(" Enter Lines of text");
System.out.println(" Enter 'stop' to quit. ");
do{ str = br.readLine( );
System.out.println(str);
}while(!str.equals("stop"));
}
}
Writing Console Output:
//Program to demonstrate System.out.write ( )
class WriteDemo {
public static void main(String args[]){
int b;
b ='A';
System.out.write(b);
System.out.write('n');
}
}
FILES:
File myFile;
myFile = new File("mydoc");
myFile = new File("/", "mydoc");
// more useful if the directory or filename is a variable.
File myDir = new File("/");
MyFile = new File(myDir, "mydoc");
• File Names:
• The following methods return file names.
• String getName( );
• String getPath( );
• String getAbsolutePath( );
• String getParent( );
• boolean renameTo(File newName);
•
• The following methods return information about file attributes.
•
• boolean exists( );
• boolean canWrite( );
• boolean isFile( );
• boolean isDirectory( );
• boolean isAbsolute( );
File Test and Utilities:

More Related Content

PPTX
Computer science input and output BASICS.pptx
RathanMB
 
PPTX
L21 io streams
teach4uin
 
PDF
UNIT4-IO,Generics,String Handling.pdf Notes
SakkaravarthiS1
 
DOCX
Oodp mod4
cs19club
 
PPTX
Stream In Java.pptx
ssuser9d7049
 
PPTX
JAVA (UNIT 3)
Dr. SURBHI SAROHA
 
PPTX
File Input and output.pptx
cherryreddygannu
 
PPTX
IOStream.pptx
HindAlmisbahi
 
Computer science input and output BASICS.pptx
RathanMB
 
L21 io streams
teach4uin
 
UNIT4-IO,Generics,String Handling.pdf Notes
SakkaravarthiS1
 
Oodp mod4
cs19club
 
Stream In Java.pptx
ssuser9d7049
 
JAVA (UNIT 3)
Dr. SURBHI SAROHA
 
File Input and output.pptx
cherryreddygannu
 
IOStream.pptx
HindAlmisbahi
 

Similar to Java development development Files lectur6.ppt (20)

DOCX
Unit IV Notes.docx
GayathriRHICETCSESTA
 
PPTX
Java I/O
Jayant Dalvi
 
PPT
Using Input Output
raksharao
 
PPTX
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
noonoboom
 
PPTX
I/O Streams
Ravi Chythanya
 
PPTX
Java Tutorial Lab 6
Berk Soysal
 
PDF
Java Day-6
People Strategists
 
PPTX
Buffer and scanner
Arif Ullah
 
PPTX
Chapter 6
siragezeynu
 
PPTX
Java Input Output (java.io.*)
Om Ganesh
 
PPT
Itp 120 Chapt 19 2009 Binary Input & Output
phanleson
 
PDF
Unit 4 - Javadfjjjjjjjjjjjjjjjaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa IO.pdf
kassyemariyam21
 
PDF
Java input output operation related introduction.
SHOUBHIK1111
 
DOC
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
uthayashangar1
 
PPTX
Java Input and Output
Ducat India
 
PPTX
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
PPTX
Io streams
Elizabeth alexander
 
PDF
Java IO Stream, the introduction to Streams
ranganadh6
 
PPTX
Input output files in java
Kavitha713564
 
PDF
Advanced programming ch2
Gera Paulos
 
Unit IV Notes.docx
GayathriRHICETCSESTA
 
Java I/O
Jayant Dalvi
 
Using Input Output
raksharao
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
noonoboom
 
I/O Streams
Ravi Chythanya
 
Java Tutorial Lab 6
Berk Soysal
 
Java Day-6
People Strategists
 
Buffer and scanner
Arif Ullah
 
Chapter 6
siragezeynu
 
Java Input Output (java.io.*)
Om Ganesh
 
Itp 120 Chapt 19 2009 Binary Input & Output
phanleson
 
Unit 4 - Javadfjjjjjjjjjjjjjjjaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa IO.pdf
kassyemariyam21
 
Java input output operation related introduction.
SHOUBHIK1111
 
Web Technology Web Technology Notes Streams Network Principles and SocketsUni...
uthayashangar1
 
Java Input and Output
Ducat India
 
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
Java IO Stream, the introduction to Streams
ranganadh6
 
Input output files in java
Kavitha713564
 
Advanced programming ch2
Gera Paulos
 
Ad

Recently uploaded (20)

PPTX
Presentation about variables and constant.pptx
safalsingh810
 
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PPTX
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PPTX
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
PPTX
oapresentation.pptx
mehatdhavalrajubhai
 
PDF
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Solar Panel Installation Guide – Step By Step Process 2025.pdf
CRMLeaf
 
PDF
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
PDF
Community & News Update Q2 Meet Up 2025
VictoriaMetrics
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
Presentation about variables and constant.pptx
safalsingh810
 
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
oapresentation.pptx
mehatdhavalrajubhai
 
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Solar Panel Installation Guide – Step By Step Process 2025.pdf
CRMLeaf
 
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
Community & News Update Q2 Meet Up 2025
VictoriaMetrics
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
Ad

Java development development Files lectur6.ppt

  • 1. File I/O in Java
  • 2. 2 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 • Three stream objects are automatically created for every application: System.in, System.out, and System.err.
  • 3. Types of Streams • There are 2 kinds of streams (1)byte streams, (2) character streams • Java programs perform I/O through streams. A stream is either a source of or a destination for bytes • Java implements streams with in class hierarchies defined in the java.io package. – InputStream Methods: – int read( ); returns an int, int read(byte[ ]); read into byte array and return the number of bytes read int read(byte[ ], int, int); The two int arguments in the third method indicate a sub range in the target array that needs to be filled. • void close( ) : When you have finished with a stream, close it
  • 4. OutputStream Methods: void write(int) void write (byte[ ]) void write(byte [ ], int, int) These methods write to the output stream void close( ): You should close output streams when you have finished with them. void flush( ): Sometimes an output stream accumulates writes before committing them. The flush ( ) method allows you to force writes.
  • 5. Basic Stream Classes: • Several stream classes are defined in the java.io package • Fig. below illustrates the hierarchy of some of the classes in that package
  • 6. 6 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
  • 7. FileInputStream and FileOutputStream: • These classes are node streams and, as the name suggests, they use disk files. The constructors for these classes allow you to specify the path of the file to which they are connected. To construct a FileInputStream, the associated file must exist and be readable. If you construct a FileOutputStream, the output file is overwritten if it already exists. FileInputStream infile = new FileInputStream("myfile.dat"); FileOutputStream outfile = new FileOutputStream(" results.dat");
  • 8. BufferedInputStream and BufferedOutputStream: • These are filter streams that should be used to increase the efficiency of I/O operations. • Basic Stream Classes: DataInputStream and DataOutputStream These filter streams allow reading and writing of Java primitive types and some special formats using streams. A number of methods are provided for the different primitives. For example: • DataInputStream Methods: byte readByte ( ) long readLong ( ) double readDouble ( )
  • 9. DataOutputStream Methods: void writeByte (byte) void writeLong(long) void writeDouble (double) Notice that the methods of DataInputStream are paired with the methods of DataOutputStream. These streams have methods for reading and writing strings. Reading Console Input: In Java, console input is accomplished by reading from System.in. To obtain a character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. BuffereredReader supports a buffered input stream. Its most commonly used constructor is shown here: BufferedReader(Reader inputReader)< br>
  • 10. Reading Console Input: • BufferedReader(Reader inputReader)< br> • Here, inputReader is the stream that is linked to the instance of BufferedReader that being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor: InputStreamReader(InputStream inputStream )
  • 11. Reading Console Input: • Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); • After this statement executes, br is a character-based stream that is linked to the console through System.in. • To read a character from a BufferedReader, use read( ). The version of read( ) that will be using is • int read( ) throws IOException
  • 12. BufferedReader to read characters from the console. // Use a BufferedReader to read characters from the console. import java.io.*; class BRRead { public static void main(String args[]) throws IOException char c; BufferedReader br = new BufferedReader(new InputStreamReader (System.in )); System.out.println("Enter characters, 'q' to quit."); // read characters do { c = (char) br.read( ); System.out.println( c); } while(c ! = 'q'); } } Output : Enter Characters, 'q' to quit Helloq H e l l o q
  • 13. Read a string from console using a BufferedReader // Read a string from console using a BufferedReader. import java.io.*; class BRReadLines { public static void main(String args[]) throws IOException{ // Create a BufferReader using System.in BufferReader br = new BufferReader (new InputStreamReader(System.in)); String str; System.out.println(" Enter Lines of text"); System.out.println(" Enter 'stop' to quit. "); do{ str = br.readLine( ); System.out.println(str); }while(!str.equals("stop")); } }
  • 14. Writing Console Output: //Program to demonstrate System.out.write ( ) class WriteDemo { public static void main(String args[]){ int b; b ='A'; System.out.write(b); System.out.write('n'); } }
  • 15. FILES: File myFile; myFile = new File("mydoc"); myFile = new File("/", "mydoc"); // more useful if the directory or filename is a variable. File myDir = new File("/"); MyFile = new File(myDir, "mydoc");
  • 16. • File Names: • The following methods return file names. • String getName( ); • String getPath( ); • String getAbsolutePath( ); • String getParent( ); • boolean renameTo(File newName); • • The following methods return information about file attributes. • • boolean exists( ); • boolean canWrite( ); • boolean isFile( ); • boolean isDirectory( ); • boolean isAbsolute( ); File Test and Utilities: