0% found this document useful (0 votes)
28 views6 pages

Input Output

Uploaded by

vishal46k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views6 pages

Input Output

Uploaded by

vishal46k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Java.

io (Input/ Output)

Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast.


The java.io package contains all the classes required for input and output operations.

A stream is a sequence of data

1) System.out: standard output stream


2) System.in: standard input stream
3) System.err: standard error stream

System.out.println("simple message");
System.err.println("error message");
int i=System.in.read();
System.out.println((char)i);

OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral
device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array, peripheral
device or socket.

OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of
bytes. An output stream output bytes and sends them to some sink.

methods of OutputStream
1) public void write(int)throws IOExceptionis used to write a byte to the current output stream.
2) public void write(byte[])throws IOException is used to write an array of byte to the current output
stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input stream of
bytes.

methods of InputStream
1) public abstract int read()throws IOException reads the next byte of data from the input stream. It
returns -1 at the end of the file.
2) public int available()throws IOException returns an estimate of the number of bytes that can be read
from the current input stream.
3) public void close()throws IOException is used to close the current input stream.

Reader and Writer classes

Reader is an abstract class for reading character streams


implementation classes are BufferedReader, CharArrayReader, FilterReader, InputStreamReader,
PipedReader, StringReader
Supported methods are
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.

Example Program: To read from a 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());
}
}
}

Writer is an abstract class for writing to character streams. The methods that a subclass must implement
are write(char[], int, int), flush(), and close().

Supported methods are:

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, int end)It appends a subsequence of the 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.

Example Program
import java.io.*;
public class WriterExample {
public static void main(String[] args) {
try {
Writer w = new FileWriter("output.txt");
String content = "I love my country";
w.write(content);
w.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
} }
Java Program to copy one file to another
import java.io.*;
import java.util.*;
public class CopyFromFileaToFileb {
public static void copyContent(File a, File b)
throws Exception
{
FileInputStream in = new FileInputStream(a);
FileOutputStream out = new FileOutputStream(b);
try {
int n;
// read() function to read the
// byte of data
while ((n = in.read()) != -1) {
// write() function to write
// the byte of data
out.write(n);
}
}
finally {
if (in != null) {
// close() function to close the
// stream
in.close();
}
// close() function to close
// the stream
if (out != null) {
out.close();
}
}
System.out.println("File Copied");
}
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in);
// get the source file name
System.out.println("Enter the source filename from where you have to read/copy :");
String a = sc.nextLine();
// source file
File x = new File(a);
// get the destination file name
System.out.println("Enter the destination filename where you have to write/paste :");
String b = sc.nextLine();
// destination file
File y = new File(b);
// method called to copy the
// contents from x to y
copyContent(x, y);
} }
Read a line of text in Java

1. Using java.util.Scanner class

Supported Methods
nextX() methods return the type of value
nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(), nextBoolean() etc.

Several Scanner Class Constructors but two are


Scanner(File source)
Scanner(InputStream source)

Example Program-1
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}

Example Program-2
import java.util.*;
public class ScannerClassExample1 {
public static void main(String args[]){
String s = "Hello, This is JavaTpoint.";
//Create scanner Object and pass string in it
Scanner scan = new Scanner(s);
//Check if the scanner has a token
System.out.println("Boolean Result: " + scan.hasNext());
//Print the string
System.out.println("String: " +scan.nextLine());
scan.close();
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
2. Using public class BufferedReader extends Reader

int read() It is used for reading a single character.


String readLine() It is used for reading a line of text.

Example Program-1:
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\test.txt");
BufferedReader br=new BufferedReader(fr);

int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}

Example Program-2:
import java.io.*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
while(!name.equals("stop")){
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}

You might also like