0% found this document useful (0 votes)
25 views20 pages

Input and Output Basics

basics of I/O and their syntax in java are explained here

Uploaded by

aaryansh2003
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
25 views20 pages

Input and Output Basics

basics of I/O and their syntax in java are explained here

Uploaded by

aaryansh2003
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 20

I/O Basics

Introduction to I/O
• Most real applications of Java are not text-based,
console programs. Rather, they are either
graphically oriented programs that rely on one of
Java’s graphical user interface (GUI) frameworks,
such as Swing, the AWT, for user interaction, or
they are Web applications.
• Although text-based, console programs are
excellent as teaching examples, they do not
constitute an important use for Java in the real
world
Streams
• Java programs perform I/O through streams. A stream is an
abstraction that either produces or consumes information. A stream is
linked to a physical device by the Java I/O system.
• All streams behave in the same manner, even if the actual physical
devices to which they are linked differ. Thus, the same I/O classes and
methods can be applied to different types of devices.
• This means that an input stream can abstract many different kinds of
input: from a disk file, a keyboard, or a network socket. Likewise, an
output stream may refer to the console, a disk file, or a network
connection. Streams are a clean way to deal with input/ output
without having every part of your code understand the difference
between a keyboard and a network,
Byte Streams and Character
Streams
• Java defines two types of streams:
byte and character.
• Byte streams provide a convenient means for handling
input and output of bytes. Byte streams are used, for
example, when reading or writing binary data.
• Character streams provide a convenient means for
handling input and output of characters. They use
Unicode and, therefore, can be internationalized.
• Also, in some cases, character streams are more
efficient than byte streams.
The Byte Stream Classes
• Byte streams are defined by
using two class hierarchies. At
the top are two abstract
classes:
• InputStream and
OutputStream.
• Each of these abstract classes
has several concrete
subclasses that handle the
differences among various
devices, such as disk , files,
network connections, and even
memory buffers.
• The abstract classes InputStream and
OutputStream define several key
methods that the other stream classes
implement.
• Two of the most important are read( )
and write( ), which, respectively, read
and write bytes of data
Character Stream Classes
Character streams are defined by
using two class hierarchies. At the
top are two abstract
classes: Reader and Writer. These
abstract classes handle Unicode
character streams
The abstract classes Reader and
Writer define several key methods
that the other stream classes
implement.
Two of the most important methods
are read( ) and write( ), which
read
and write characters of data,
respectively
Use a BufferedReader to read characters
from the console (Example)
• 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');
• }
• }
Reading a String
• class BRReadLines {
• public static void main(String args[]) throws IOException
• {
• // create a BufferedReader using System.in
• BufferedReader br = new BufferedReader(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"));
• }}
Program to Store 100 line (read from
console )
import java.io.*;
class TinyEdit {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str[] = new String[100];
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
for(int i=0; i<100; i++) {
str[i] = br.readLine();
if(str[i].equals("stop")) break;
}
System.out.println("\nHere is your file:");
// display the lines
for(int i=0; i<100; i++) {
if(str[i].equals("stop")) break;
System.out.println(str[i]);
}}}
Writing Console Output
• Console output is most easily // Demonstrate System.out.write().
accomplished with print( ) and println( ). class WriteDemo {
public static void main(String args[]){
• These methods are defined by the class
int b;
PrintStream (which is the type of object b = 'A';
referenced by System.out). System.out.write(b);
• Even though System.out is a byte System.out.write('\n');
stream, using it for simple program output }
is still acceptable. }

• Because PrintStream is an output stream


derived from OutputStream, it also
implements the low-level method
write( ). Thus, write( ) can be used to
write to the console.
Print Writer Method
• PrintWriter pw = new PrintWriter(System.out, true);
• The following application illustrates using a PrintWriter to handle console output:
• // Demonstrate PrintWriter
• import java.io.*;
• public class PrintWriterDemo {
• public static void main(String args[]) {
• PrintWriter pw = new PrintWriter(System.out, true);
• pw.println("This is a string");
• int i = -7;
• pw.println(i);
• double d = 4.5e-7;
• pw.println(d);
• }
• }
BufferReader class for Files
import java.io.*;
• BufferReader class also used public class Filereader {
to read input from files. public static void main(String[] args)
throws IOException {
FileReader fr = new FileReader("C:\\Users\\
rajeshk\\eclipse-workspace\\rajesh\\src\\
new.txt");
BufferedReader br = new BufferedReader(fr);
int s;
while((s=br.read())!=-1){

System.out.print((char)s);
// System.out.println(s);
}}

}
The methods present in File class(java.io.File):
SL. No. Method Return Type Description
This method checks whether
1. canRead() Boolean
the file is readable or not.
This method creates a new
file in the desired path. The
2. createNewFile() Boolean
file created is generally
empty.
This method checks whether
3. canWrite() Boolean the file is writable or not,i.e,
not a read-only file.
This method verifies if the file
4. exists() Boolean asked for is present or not in
the directory.
This method is used to delete
5. delete() Boolean
a file from the directory.
This method helps us find the
6. getName() String name of a particular file from
the directory.
This method returns the
7. getAbsolutePath() String absolute path of the given
file.
This method returns the size
8. length() Long
of a file in bytes.
This method returns an array,
listing all the files present in
9. list() String[]
the present working
directory(PWD).
Creating a file
import java.io.File;
import java.io.IOException;
public class file {
public static void main(String args[])throws IOException
{
try {
File fcreate = new File("C:\\Users\\rajeshk\\eclipse-workspace\\rajesh\\
src\\file.txt");
if (fcreate.createNewFile()) {
System.out.println("File " + fcreate.getName() + " is created
successfully.");
}
else {
System.out.println("File is already exist in the
directory.");
}
} catch (IOException exception) {
System.out.println("An unexpected error is occurred.");
exception.printStackTrace();
}
}
}
Methods for File Information
import java.io.File;
public class FileInformation
{
public static void main(String[] args) {
File finfo = new File("G:\\Internship\\File Handling\\NewFile.txt");
if (finfo.exists()) {
System.out.println("The name of the file is: " + finfo.getName());
System.out.println("The absolute path of the file is: " + finfo.getAbsolutePath());
System.out.println("Is file writeable: " + finfo.canWrite());
System.out.println("Is file readable: " + finfo.canRead());
System.out.println("The size of the file is: " + finfo.length());
} else {
System.out.println("The file does not exist.");
}
}
}
Using java FileWriter:
The character stream contains the FileWriter class, which can write 16-bits of data at a time into a
file. This is a much quicker technique compared to OutputStreamWriter as 16 bits of data is
written at a time.
import java.io.FileWriter;
import java.io.IOException;
public class CharacterStreamWrite
{
public static void main(String[] args) {
try {
FileWriter fwrite = new FileWriter("G:\\Internship\\File Handling\\NewFile.txt");
fwrite.write("Written using FileWriter!!!");
fwrite.close();
} catch (IOException e) {
System.out.println("Error While Writing!!!");
e.printStackTrace();
}
}
}
Using java FileReader:
import java.io.FileReader;
public class CharacterStreamRead
{
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader("G:\\Internship\\File Handling\\
NewFile.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Deleting a File in Java:
import java.io.File;
public class DeleteFile
{
public static void main(String[] args)
{
File fdel = new File("G:\\Internship\\File Handling\\NewFile.txt");
if (fdel.delete())
{
System.out.println(fdel.getName()+ " is deleted successfully.");
}
else
{
System.out.println("Could Not Delete File");
}
}
}
Command Line arguments
public class commandLine {

public static void main(String args[]) {


for (int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}}

You might also like