0% found this document useful (0 votes)
28 views

Unit 06 Managing InputOutput Files in Java

Uploaded by

Harish Khojare
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Unit 06 Managing InputOutput Files in Java

Uploaded by

Harish Khojare
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Unit 06 Managing Input/Output Files in Java

Concept of Stream Classes


 In Java, a stream is a path along which the data flows.
 Every stream has a source and a destination.
 We can build a complex file processing sequence using a series of simple stream operations.
 Two fundamental types of streams are Writing streams and Reading streams.
 While an Writing streams writes data into a destination (file)
 An Reading streams is used to read data from a source(file).
Java Stream Classes
Standard Stream in Java

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

Standard Input − This is used to feed the data to user's program and usually a keyboard is used as
standard input stream and represented as System.in.

Standard Output − This is used to output the data produced by the user's program and usually a
computer screen is used for standard output stream and represented as System.out.

Standard Error − This is used to output the error data produced by the user's program and usually a
computer screen is used for standard error stream and represented as System.err.
OutputStream class
OutputStream class is an abstract class.
It is the superclass of all classes representing an output stream of bytes.
An output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream

Method Description

1) public void write(int)throws is used to write a byte to the current


IOException output stream.
2) public void write(byte[])throws is used to write an array of byte to the
IOException current output stream.
3) public void flush()throws flushes the current output stream.
IOException
4) public void close()throws is used to close the current output
IOException stream.
FileOutputStream class
FileOutputStream class declaration
public class FileOutputStream extends OutputStream

FileOutputStream class methods


1. protected void finalize(): It is used to clean up the connection with the file output stream.
2. void write(byte[] ary):It is used to write ary.length bytes from the byte array to the file output
stream.
3. void write(byte[] ary, int off, int len) :It is used to write len bytes from the byte array starting
at offset off to the file output stream.
4. void write(int b): It is used to write the specified byte to the file output stream.
5. FileChannel getChannel(): It is used to return the file channel object associated with the file
output stream.
6. FileDescriptor getFD(): It is used to return the file descriptor associated with the stream.
7. void close() : It is used to closes the file output stream
FileOutputStream Example1

import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
FileOutputStream Example 2

import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array, peripheral
device or socket
InputStream class is an abstract class.
It is the superclass of all classes representing an input stream of bytes.

Useful methods of InputStream

Method Description

1) public abstract int read()throws reads the next byte of data from
IOException the input stream. It returns -1 at
the end of the file.
2) public int available()throws returns an estimate of the number
IOException of bytes that can be read from the
current input stream.
3) public void close()throws is used to close the current input
IOException stream.
FileInputStream Class
Java Java FileInputStream class obtains input bytes from a file.
It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc.
Java FileInputStream class declaration
public class FileInputStream extends InputStream
Method Description
int available() It is used to return the estimated number of bytes that can
be read from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the
input stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the input
stream.
long skip(long x) It is used to skip over and discards x bytes of data from
the input stream.
FileChannel getChannel() It is used to return the unique FileChannel object
associated with the file input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.
protected void finalize() It is used to ensure that the close method is call when
there is no more reference to the file input stream.

void close() It is used to closes the stream.


FileInputStream example 1: read single character

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Character Stream Classes

 It provides support for managing I/O operations on characters.

 Classes Reader and Writer are operated on characters for reading and writing, respectively.
 Character streams can be used to read and write 16-bit Unicode characters.
 Reader stream classes are designed to read character from the files and writer stream classes are
designed to perform all output operations on files.
 The primary advantage of character streams is that they make it easy to write programs that are
not dependent upon a specific character encoding, and are therefore easy to internationalize
Reader Stream Class

 Reader stream classes are designed to read character from the files.

 Reader is designed to handle characters; therefore reader classes can perform all the functions
implemented by the input stream classes.
 It is used to read the 16-bit characters from the input stream.
 However, it is an abstract class and can't be instantiated, but there are various subclasses that
inherit the Reader class and override the methods of the Reader class.
 All methods of the Reader class throw an IOException.
Subclasses of the Reader class

SN Class Description

1. BufferedReader This class provides methods to read characters from the buffer.

2. CharArrayReader This class provides methods to read characters from the char
array.
3. FileReader This class provides methods to read characters from the file.

4. FilterReader This class provides methods to read characters from the


underlying character input stream.
5 InputStreamReader This class provides methods to convert bytes to characters.
6 PipedReader This class provides methods to read characters from the
connected piped output stream.
7 StringReader This class provides methods to read characters from a string.
Reader class Methods
abstract void close() It closes the stream and releases
any system resources associated
with it.
void mark(int readAheadLimit) It marks the present position in the
stream.
boolean markSupported() It tells whether this stream
supports the mark() operation.
int read() It reads a single character.
int read(char[] cbuf) It reads characters into an array.
abstract int read(char[] cbuf, int off, int len) It reads characters into a portion of
an array.
int read(CharBuffer target) It attempts to read characters into
the specified character buffer.
boolean ready() It tells whether this stream is ready
to be read.
void reset() It resets the stream.
long skip(long n) It skips characters.
Reader Class Example

import java.io.*;
public class ReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("file.txt");
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
reader.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Java Writer
It is an abstract class for writing to character streams.
The methods that a subclass must implement are write(char[], int, int), flush(), and close().
Modifier and Type Method Description
Writer append(char c) It appends the specified character to
this writer.
Writer append(CharSequence csq) It appends the specified character
sequence to this writer
Writer append(CharSequence csq, int start, It appends a subsequence of the
int end) specified character sequence to this
writer.
abstract void close() It closes the stream, flushing it first.
abstract void flush() It flushes the stream.
void write(char[] cbuf) It writes an array of characters.
abstract void write(char[] cbuf, int off, int len) It writes a portion of an array of
characters.
void write(int c) It writes a single character.
void write(String str) It writes a string.
void write(String str, int off, int len) It writes a portion of a string.
Java FileWriter Class

 Java FileWriter class is used to write character-oriented data to a file.


 It is character-oriented class which is used for file handling in java.
 Syntax : public class FileWriter extends OutputStreamWriter

Constructors of FileWriter class


Constructor Description

FileWriter(String file) Creates a new file. It gets file


name in string.
FileWriter(File file) Creates a new file. It gets file
name in File object.
Methods of FileWriter class

Method Description

void write(String text) It is used to write the string into


FileWriter.

void write(char c) It is used to write the char into


FileWriter.

void write(char[] c) It is used to write char array into


FileWriter.

void flush() It is used to flushes the data of


FileWriter.

void close() It is used to close the FileWriter.


Java FileWriter Example

import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to java.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
Java File Class
The File class have several methods for working with directories and files such as creating new directories or
files, deleting and renaming directories or files, listing the contents of a directory etc.

Constructor Description

File(File parent, String child) It creates a new File instance from a


parent abstract pathname and a child
pathname string.
File(String pathname) It creates a new File instance by
converting the given pathname string
into an abstract pathname.
File(String parent, String child) It creates a new File instance from a
parent pathname string and a child
pathname string.
File(URI uri) It creates a new File instance by
converting the given file: URI into an
abstract pathname.
Java File Class Methods
Modifier and Type Method Description
static File createTempFile(String prefix, String suffix) It creates an empty file in the default
temporary-file directory, using the given
prefix and suffix to generate its name.
boolean createNewFile() It atomically creates a new, empty file
named by this abstract pathname if and only
if a file with this name does not yet exist.
boolean canWrite() It tests whether the application can modify
the file denoted by this abstract
pathname.String[]
boolean canExecute() It tests whether the application can execute
the file denoted by this abstract pathname.
boolean canRead() It tests whether the application can read the
file denoted by this abstract pathname.
boolean isAbsolute() It tests whether this abstract pathname is
absolute.
boolean isDirectory() It tests whether the file denoted by this
abstract pathname is a directory.
boolean isFile() It tests whether the file denoted by this
abstract pathname is a normal file.
String getName() It returns the name of the file or directory
denoted by this abstract pathname.
String getParent() It returns the pathname string of this
abstract pathname's parent, or null if this
pathname does not name a parent directory.
Path toPath() It returns a java.nio.file.Path object
constructed from the this abstract path.
Java File Class Example
import java.io.*;
public class FileDemo {
public static void main(String[] args) {

try {
File file = new File("javaFile123.txt");
if (file.createNewFile()) {
System.out.println("New File is created!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}

}
}
Java Scanner

 Scanner class in Java is found in the java.util package.


 Java provides various ways to read input from the keyboard, the java.util.Scanner class is
one of them
 To get the instance of Java Scanner which reads input from the user, we need to pass the
input stream (System.in) in the constructor of Scanner class.

Syntax: Scanner in = new Scanner(System.in);


Scanner Class Example
import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);

System.out.println("Enter name, age and salary:");

// String input
String name = myObj.nextLine();

// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();

// Output input by user


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Copy one File to another Example
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyExample {


public static void main(String[] args) {
FileInputStream ins = null;
FileOutputStream outs = null;
try {
File infile = new File(“D:\\java programs\\abc.txt");
File outfile = new File(“D:\\java programs\\bbc.txt");
ins = new FileInputStream(infile);
outs = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;

while ((length = ins.read(buffer)) > 0) {


outs.write(buffer, 0, length);
}
ins.close();
outs.close();
System.out.println("File copied successfully!!");
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
Thank You !

You might also like