Unit 06 Managing InputOutput Files in Java
Unit 06 Managing InputOutput Files 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.
Method Description
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.
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.
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
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.
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
Method Description
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
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
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();