Download IOPackage - WordPress.com

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java IO Packages
Prepared by
Mrs.S.Amudha AP/SWE
Introduction
• The Java Input/Output (I/O) is a part of java.io
package.
• The java.io package contains a relatively large
number of classes
• The classes in the package are primarily abstract
classes and stream-oriented
• Define methods and subclasses for allowing
bytes to be read from and written to files or other
2
input and output sources
File
• A File object is used to obtain or manipulate the
information associated with a disk file
• Such as the permissions, time, date, and directory
path
• Files are a primary source and destination for
data within many programs
• Constructors
– File(String directoryPath)
– File(String directoryPath, String filename)
– File(File dirObj, String filename)
3
What Are Streams?
• Is a path of communication between the source
of some information and its destination
• Producers and consumers of bytes
• Example
– Input stream - allows you to read data from a source
– Output stream - allows you to write data to a
destination.
4
Hierarchy structure
5
InputStream
• Is used for reading the data such as a byte and
array of bytes from an input source
• An input source can be a file, a string, or
memory that may contain the data
• It is an abstract class that defines the
programming interface for all input streams
that are inherited from it
• An input stream is automatically opened
when you create it.
6
InputStream hierarchy
7
Abstract Class InputStream
• Is an abstract class that defines the fundamental
ways in which a destination (consumer) reads a
stream of bytes from some source.
• The identity of the source, and the manner of the
creation and transport of the bytes, is
irrelevant.
8
ByteArray I/p Stream
Example
// Demonstrate ByteArrayInputStream.
import java.io.*;
class ByteArrayInputStreamDemo {
public static void main(String args[]) throws IOException {
String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[] = tmp.getBytes();
ByteArrayInputStream input1 = new ByteArrayInputStream(b);
ByteArrayInputStream input2 = new ByteArrayInputStream(b,
0,3); } }
9
FileReader
• The FileReader class creates a Reader that you
can use to read the contents of a file
• Constructor
– FileReader(String filePath)
– FileReader(File fileObj)
10
Example
// Demonstrate FileReader.
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("FileReaderDemo.java");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}
11
CharArrayReader
• CharArrayReader is an implementation of an
input stream that uses a character array as
the source.
• This class has two constructors
– CharArrayReader(char array[ ])
– CharArrayReader(char array[ ], int start, int
numChars)
12
Example
import java.io.*;
public class CharArrayReaderDemo {
public static void main(String args[]) throws IOException {
String tmp = "abcdefghijklmnopqrstuvwxyz";
int length = tmp.length(); char c[] = new char[length]; tmp.getChars(0,
length, c, 0);
CharArrayReader input1 = new CharArrayReader(c);
CharArrayReader input2 = new CharArrayReader(c, 0, 5);
int i;
System.out.println("input1 is:");
while((i = input1.read()) != -1) {
System.out.print((char)i); }
System.out.println();
System.out.println("input2 is:");
while((i = input2.read()) != -1) {
System.out.print((char)i) ; }
System.out.println();13}
}
OutputStream




Is a sibling to InputStream that is used for
writing byte and array of bytes to an output
source
An output source can be anything such as a file, a
string, or memory containing the data
An output stream is automatically opened when
you create it
You can explicitly close an output stream with
the close( ) method, or let it be closed implicitly
when the object is garbage collected 14
OutputStream hierarchy
15
How Files and Streams Work
16
Classes and Interfaces
Class
Description
BufferedInputStream
It used for creating an internal buffer array. It supports the mark
and reset methods.
BufferedOutputStream
This class used for writes byte to output stream. It implements a
buffered output stream.
BufferedReader
This class provides read text from character input stream and
buffering characters.(reads characters, arrays and lines)
BufferedWriter
This class provides write text from character output stream and
buffering characters( writes characters, arrays and lines.)
ByteArrayInputStream
It contains the internal buffer and read data from the stream.
ByteArrayOutputStream
This class used for data is written into byte array. This is
implement in output stream class.
17
Exceptions Classes
Exceptions
Description
CharConversionException
It provides detail message in the catch block to associated
with the CharConversionException
EOFException
This exception indicates the end of file.
FileNotFoundException
When the open file's pathname does not find then this
exception to be occured.
InterruptedIOException
When the I/O operations to interrupted from any causes
then it becomes.
InvalidClassException
Any problems to be created with class, when the
Serializing runtime to be detected.
InvalidObjectException
When the de-serialized objects failed then it occurs.
18
Reading Text from the Standard Input
* Standard Input: Accessed through System.in
which is used to read input from the keyboard.
* Standard Output: Accessed through
System.out which is used to write output to be
display.
* Standard Error: Accessed through System.err
which is used to write error output to be display.
• Syntax:
InputStreamReader inp = new
InputStreamReader(system.in);
19
BufferedReader
• The BufferedReader class is the subclass of the Reader
class.
• It reads character-input stream data from a memory area
known as a buffer maintains state.
• The buffer size may be specified, or the default size may be
used
Constructor
• BufferedReader(Reader in):Creates a buffering characterinput stream that uses a default-sized input buffer
• BufferedReader(Reader in, int sz): Creates a buffering
character-input stream that uses an input buffer of the
specified size.
20
Example
import java.io.*;
public class ReadStandardIO{
public static void main(String[] args)
throws IOException{
InputStreamReader inp = new
InputStreamReader(System.in)
BufferedReader br = new
BufferedReader(inp);
System.out.println("Enter text : ");
String str = br.readLine();
System.out.println("You entered
String : ");
System.out.println(str);
}
}
Output:
C:\java>javacReadSta
ndardIO.java
C:\java>java
ReadStandardIO
Enter text :
this is an Input
Stream
You entered String :
this is an Input
Stream
21
C:\java>
Working With File
The constructors of the File class are shown in the
table:
Constructor
- Description
• File(path)
- Create File object for default
directory (usually where program is located).
• File(dirpath,fname) - Create File object for
directory path given as string.
• File(dir, fname) - Create File object for
directory.
Thus the statement can be written as: 22
Methods
Method
Description
f.exists()
Returns true if file exists.
f.isFile()
Returns true if this is a normal file.
f.isDirectory()
f.getName()
f.length()
f.getPath()
true if "f" is a directory.
Returns name of the file or directory.
Returns number of bytes in file.
path name.
23
Create a File
• For creating a new file File.createNewFile( )
method is used.
• This method returns a boolean value true if the
file is created otherwise return false.
• If the mentioned file for the specified directory
is already exist then the createNewFile()
method returns the false otherwise the method
creates the mentioned file and return true.
24
Example
import java.io.*;
public class CreateFile1{
public static void main(String[] args) throws
IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()){
f.createNewFile();
System.out.println("New file \"myfile.txt\" has
been created to the current directory"); } } }
25
Read file line by line
• Java supports the following I/O file streams.
* FileInputstream
* FileOutputStream
FileInputstream:
This class is a subclass of Inputstream class that reads
bytes from a specified file name . The read() method
of this class reads a byte or array of bytes from the
file. It returns -1 when the end-of-file has been
reached.
26
Read file line by line
FileOutputStream:
This class is a subclass of OutputStream that writes
data to a specified file name.
• The write() method of this class writes a byte or
array of bytes to the file.
DataInputStream:
• This class is a type of FilterInputStream that
allows you to read binary data of Java primitive
data types in a portable way.
27
Example
import java.io.*;
public class ReadFile{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()&& f.length()<0)
System.out.println("The specified file is not exist");
else{
FileInputStream finp=new FileInputStream(f);
byte b;
do{
b=(byte)finp.read();
System.out.print((char)b);
}
while(b!=-1);
finp.close();
} } }
28
Write To File
FileOutputStream class is used to write data to a
file.
FileWriter is a subclass of OutputStreamWriter
class that is used to write text (as opposed to binary
data) to a file
The BufferedWriter class is used to write text to a
character-output stream, buffering characters so as
to provide for the efficient writing of single
characters, arrays and strings.
29
Example
import java.io.*;
public class FileWriter{
public static void main(String[] args) throws
IOException{
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Please enter the file name to
create : ");
String file_name = in.readLine();
File file = new File(file_name);
30
boolean exist = file.createNewFile();
Append To File
import java.io.*;
class FileWrite
{
public static void main(String args[]) {
try{
// Create file
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
31}
} }
Getting the Size of a File
import java.io.*;
public class FileSize{
public static void main(String[] args) throws IOException{
System.out.print("Enter file name : ");
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
File f = new File(in.readLine());
if(f.exists()){
long file_size = f.length();
System.out.println("Size of the file : " + file_size);
}
else{
System.out.println("File does not exists.");
System.exit(0);
} } }
32
Create Temp File
import java.io.File;
import java.io.FileWriter;
mport java.io.BufferedWriter;
import java.io.IOException;
public class CTFile {
public static void main(String[] args){
File tempFile = null;
try {
tempFile = File.createTempFile("MyFile.txt", ".tmp" );
System.out.print("Created temporary file with name ");
System.out.println(tempFile.getAbsolutePath());
} catch (IOException ex) {
System.err.println("Cannot create temp file: " + ex.getMessage());
} finally {
if (tempFile != null) {
}
}
} }
33
Example
import java.io.*;
public class SquareNum {
public double square(double num) {
return num * num;
}
public double getNumber() throws IOException {
// create a BufferedReader using System.in
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader inData = new BufferedReader(isr);
String str;
str = inData.readLine();
return (new Double(str)).doubleValue();
}
public static void main(String args[]) throws IOException {
SquareNum ob = new SquareNum();
double val;
System.out.println("Enter value to be squared: ");
val = ob.getNumber();
val = ob.square(val);
System.out.println("Squared value is " + val);
34
} }
Serialization
• Serialization is the process of writing the state of
an object to a byte stream
• Serialization is also needed to implement Remote
Method Invocation (RMI)
• An object that implements the Serializable
interface can be saved and restored by the
serialization facilitie
35
Stream Benefits
• Streaming interface to I/O in Java provides a
clean abstraction for a complex task
• Filtered stream classes allows you to dynamically
build the custom streaming interface to suit your
data transfer requirements.
• InputStream, OutputStream, Reader, and
Writer classes will function properly
36
37