0% found this document useful (0 votes)
34 views18 pages

Java I/O Streams: Input & Output Basics

The document provides an overview of I/O basics in Java, detailing input and output streams, including byte and character streams, along with their respective classes and methods. It also covers string handling in Java, highlighting the immutability of strings, various string methods, and the use of StringBuilder for mutable strings. Additionally, it includes examples of reading and writing files using different classes such as FileInputStream, FileOutputStream, BufferedInputStream, and BufferedOutputStream.

Uploaded by

Ragavan Murali
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)
34 views18 pages

Java I/O Streams: Input & Output Basics

The document provides an overview of I/O basics in Java, detailing input and output streams, including byte and character streams, along with their respective classes and methods. It also covers string handling in Java, highlighting the immutability of strings, various string methods, and the use of StringBuilder for mutable strings. Additionally, it includes examples of reading and writing files using different classes such as FileInputStream, FileOutputStream, BufferedInputStream, and BufferedOutputStream.

Uploaded by

Ragavan Murali
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

I/O Basics - Reading Console Input - Writing Console Output.

String
Handling: String - String Buffer - String Builder
I/O Basics
In Java, streams are the sequence of data that are read from the source and written
to the destination.
An input stream is used to read data from the source. And, an output stream is
used to write data to the destination.

Types of Streams
Depending upon the data a stream holds, it can be classified into:
• Byte Stream
• Character Stream
Byte stream
Byte stream is used to read and write a single byte (8 bits) of data.
All byte stream classes are derived from base abstract classes
called InputStream and OutputStream.
Character Stream
Character stream is used to read and write a single character of data.

1
All the character stream classes are derived from base abstract
classes Reader and Writer.
InputStream Class

The InputStream class of the [Link] package is an abstract superclass that


represents an input stream of bytes.
Since InputStream is an abstract class, it is not useful by itself. However, its
subclasses can be used to read data.
Subclasses of InputStream
In order to use the functionality of InputStream, we can use its subclasses. Some of
them are:

• FileInputStream
• ByteArrayInputStream
• ObjectInputStream

Create an InputStream
In order to create an InputStream, we must import the [Link] package
first.
FileInputStream object1 = new FileInputStream();

Methods of InputStream
The InputStream class provides different methods that are implemented by its
subclasses. Here are some of the commonly used methods:
• read() - reads one byte of data from the input stream
• read(byte[] array) - reads bytes from the stream and stores in the specified
array
• available() - returns the number of bytes available in the input stream
• mark() - marks the position in the input stream up to which data has been
read
• reset() - returns the control to the point in the stream where the mark was set

2
• markSupported() - checks if the mark() and reset() method is supported in
the stream
• skips() - skips and discards the specified number of bytes from the input
stream
• close() - closes the input stream

Example: FileInputStream Using FileInputStream


Here is how we can implement InputStream using the FileInputStream class.
Suppose we have a file named [Link] with the following content.
This is a line of text inside the file.
import [Link];
import [Link];
class Main
{
public static void main(String args[]) {
byte[] array = new byte[100];
try {
InputStream input = new FileInputStream("[Link]");
[Link]("Available bytes in the file: " + [Link]());
// Read byte from the input stream
[Link](array);
[Link]("Data read from the file: ");
// Convert byte array into string
String data = new String(array);
[Link](data);
// Close the input stream
[Link]();
}
catch (Exception e) {

3
[Link]();
}
}
}

Java OutputStream Class


The OutputStream class of the [Link] package is an abstract superclass that
represents an output stream of bytes.
Since OutputStream is an abstract class, it is not useful by itself. However, its
subclasses can be used to write data.

Subclasses of OutputStream
In order to use the functionality of OutputStream, we can use its subclasses. Some
of them are:
• FileOutputStream
• ByteArrayOutputStream
• ObjectOutputStream
Create an OutputStream
In order to create an OutputStream, we must import the [Link]
package first. Once we import the package, here is how we can create the output
stream.
OutputStream object = new FileOutputStream();

Methods of OutputStream
The OutputStream class provides different methods that are implemented by its
subclasses. Here are some of the methods:
• write() - writes the specified byte to the output stream
• write(byte[] array) - writes the bytes from the specified array to the output
stream

4
• flush() - forces to write all data present in output stream to the destination
• close() - closes the output stream

Example: OutputStream Using FileOutputStream

import [Link];
import [Link];

public class Main {

public static void main(String args[]) {


String data = "This is a line of text inside the file.";
try {
FileOutputStream out = new FileOutputStream("[Link]");
// Converts the string into bytes
byte[] dataBytes = [Link]();
// Writes data to the output stream
[Link](dataBytes);
[Link]("Data is written to the file.");
// Closes the output stream
[Link]();
}
catch (Exception e) {
[Link]();
}
}
}

5
Java BufferedInputStream Class

The BufferedInputStream class of the [Link] package is used with other input
streams to read the data (in bytes) more efficiently.
Working of BufferedInputStream

The BufferedInputStream maintains an internal buffer of 8192 bytes.


During the read operation in BufferedInputStream, a chunk of bytes is read from the
disk and stored in the internal buffer. And from the internal buffer bytes are read
individually.
// Creates a FileInputStream
FileInputStream file = new FileInputStream(String path);
// Creates a BufferedInputStream
BufferedInputStream buffer = new BufferInputStream(file);

import [Link];
import [Link];

class Main
{
public static void main(String[] args) {
try {

// Creates a FileInputStream
FileInputStream file = new FileInputStream("[Link]");
// Creates a BufferedInputStream
BufferedInputStream input = new BufferedInputStream(file);

// Reads first byte from file


int i = input .read();

6
while (i != -1) {
[Link]((char) i);
// Reads next byte from the file
i = [Link]();
}
[Link]();
}

catch (Exception e) {
[Link]();
}
}
}

Create a BufferedOutputStream
The BufferedOutputStream class of the [Link] package is used with other output
streams to write the data (in bytes) more efficiently.
// Creates a FileOutputStream
FileOutputStream file = new FileOutputStream(String path);

// Creates a BufferedOutputStream
BufferedOutputStream buffer = new BufferOutputStream(file);

Methods of BufferedOutputStream

The BufferedOutputStream class provides implementations for different methods


in the OutputStream class.

7
write() Method

• write() - writes a single byte to the internal buffer of the output stream
• write(byte[] array) - writes the bytes from the specified array to the output
stream
• write(byte[] arr, int start, int length) - writes the number of bytes equal
to length to the output stream from an array starting from the position start
Example: BufferedOutputStream to write data to a File

import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
String data = "This is a line of text inside the file";
try {
// Creates a FileOutputStream
FileOutputStream file = new FileOutputStream("[Link]");
// Creates a BufferedOutputStream
BufferedOutputStream output = new BufferedOutputStream(file);
byte[] array = [Link]();

// Writes data to the output stream


[Link](array);
[Link]();
}

catch (Exception e) {
[Link]();

8
}
}
}
flush() Method

To clear the internal buffer, we can use the flush() method. This method forces the
output stream to write all data present in the buffer to the destination file.
Java Reader Class

The Reader class of the [Link] package is an abstract superclass that represents a
stream of characters.
Subclasses of Reader

In order to use the functionality of Reader, we can use its subclasses. Some of them
are:
• BufferedReader
• InputStreamReader
• FileReader
• StringReader

Methods of Reader

The Reader class provides different methods that are implemented by its
subclasses. Here are some of the commonly used methods:
• ready() - checks if the reader is ready to be read
9
• read(char[] array) - reads the characters from the stream and stores in the
specified array
• read(char[] array, int start, int length) - reads the number of characters equal
to length from the stream and stores in the specified array starting from
the start
• mark() - marks the position in the stream up to which data has been read
• reset() - returns the control to the point in the stream where the mark is set
• skip() - discards the specified number of characters from the stream
Java Writer Class

The Writer class of the [Link] package is an abstract superclass that represents a
stream of characters.

Methods of Writer

The Writer class provides different methods that are implemented by its subclasses.
Here are some of the methods:
• write(char[] array) - writes the characters from the specified array to the
output stream
• write(String data) - writes the specified string to the writer
• append(char c) - inserts the specified character to the current writer
• flush() - forces to write all the data present in the writer to the corresponding
destination
• close() - closes the writer
To write a file line by line using File Writer

Steps to append text to a file In Java 6

1. Open the file you want to append text using FileWriter in append mode by
passing true
2. Wrap FileWriter into BufferedReader if you are going to write large text
3. Wrap PrintWriter if you want to write in a new line each time
4. Close FileWriter in finally block to avoid leaking file descriptors

10
import [Link].*;
class WriteDemo
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("enter the data");

String ename= [Link]();


int eno=[Link]([Link]());
String Address = [Link]();

FileWriter fw = new FileWriter("[Link]", true);


BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw,true);
[Link](ename +" "+eno+" "+Address);
[Link]("Data Successfully appended into file");
[Link]();
}
}

To read a file line by line using Scanner

import [Link].*;
class ReadDemo
{

11
public static void main(String args[]) throws IOException
{
Scanner s = new Scanner(new FileInputStream("[Link]"));
while([Link]())
{
[Link]([Link]());
}
}
}

To read a file line by line using Buffered Reader


import [Link].*;
class ReadDemo2
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String s = [Link]();
while(s!=null)
{
[Link](s);
s = [Link]();
}
}
}

12
Java Strings

In Java, a string is a sequence of characters. For example, "hello" is a string


containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
class Main {
public static void main(String[] args) {

// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";

// print strings
[Link](first); // print Java
[Link](second); // print Python
[Link](third); // print JavaScript
}
}
Get the Length of a String

To find the length of a string, we use the length() method.


Join Two Java Strings

We can join two strings in Java using the concat() method.


Compare Two Strings

In Java, we can make comparisons between two strings using the equals() method.

13
Java Strings are Immutable

In Java, strings are immutable. This means once we create a string, we cannot change
that string.
Methods of Java String
Besides those mentioned above, there are various string methods present in Java.
Here are some of those methods:

Methods Description

contains() Checks whether the string contains a substring.

substring() Returns the substring of the string.

join() Joins the given strings using the delimiter.

Replaces the specified old character with the


replace()
specified new character.

replaceAll() Replaces all substrings matching the regex pattern.

replaceFirst() Replaces the first matching substring.

Returns the character present in the specified


charAt()
location.

getBytes() Converts the string to an array of bytes.

Returns the position of the specified character in the


indexOf()
string.

compareTo() Compares two strings in the dictionary order.

compareToIgnoreCase() Compares two strings, ignoring case differences.

14
trim() Removes any leading and trailing whitespaces.

format() Returns a formatted string.

split() Breaks the string into an array of strings.

toLowerCase() Converts the string to lowercase.

toUpperCase() Converts the string to uppercase.

Returns the string representation of the specified


valueOf()
argument.

toCharArray() Converts the string to a char array.

matches() Checks whether the string matches the given regex.

startsWith() Checks if the string begins with the given string.

endsWith() Checks if the string ends with the given string.

isEmpty() Checks whether a string is empty or not.

intern() Returns the canonical representation of the string.

contentEquals() Checks whether the string is equal to charSequence.

hashCode() Returns a hash code for the string.

Java StringBuilder Class

Java StringBuilder class is used to create mutable (modifiable) String.

15
Important methods of StringBuilder class

Method Description

public StringBuilder It is used to append the specified string with this


append(String s) string. The append() method is overloaded like
append(char), append(boolean), append(int),
append(float), append(double) etc.

public StringBuilder It is used to insert the specified string with this string
insert(int offset, String s) at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.

public StringBuilder It is used to replace the string from specified


replace(int startIndex, int startIndex and endIndex.
endIndex, String str)

public StringBuilder It is used to delete the string from specified startIndex


delete(int startIndex, int and endIndex.
endIndex)

public StringBuilder It is used to reverse the string.


reverse()

public int capacity() It is used to return the current capacity.

public void It is used to ensure the capacity at least equal to the


ensureCapacity(int given minimum.
minimumCapacity)

16
public char It is used to return the character at the specified
charAt(int index) position.

public int length() It is used to return the length of the string i.e. total
number of characters.

public String It is used to return the substring from the specified


substring(int beginIndex) beginIndex.

public String It is used to return the substring from the specified


substring(int beginIndex, int beginIndex and endIndex.
endIndex)

A list of differences between StringBuffer and StringBuilder is given below:


No. StringBuffer StringBuilder

1) StringBuffer is synchronized i.e. StringBuilder is non-


thread safe. It means two threads synchronized i.e. not thread safe. It
can't call the methods of StringBuffer means two threads can call the
simultaneously. methods of StringBuilder
simultaneously.

2) StringBuffer is less efficient than StringBuilder is more efficient than


StringBuilder. StringBuffer.

3) StringBuffer was introduced in Java StringBuilder was introduced in Java


1.0 1.5

public class StringBufferExample


{
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("She sells sea shells ");
[Link]("Given stringbuffer is: " + sb);
[Link]("length of stringbuffer is: " + [Link]() + ", ca
pacity of stringbuffer is: " + [Link]());

17
[Link]("character at index 5 of the stringbuffer is: " + s
[Link](5));
[Link]("codePointAt index 5 of the stringbuffer is: " +
[Link](5));
[Link]("appendind the stringbuffer: " + [Link]("on
the sea shore"));
[Link]("substring of stringbuffer from index 10 to 20 i
s: " + [Link](10,20));
[Link]("reverse of the stringbuffer is: " + [Link]());
}
}

18

You might also like