String and I/O

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 91

String and I/O

• Strings are treated differently in Java compared to C


language;
• In the latter case, it represents an array of characters
terminated by null character.
• In Java, a string is an object of a class, and there is no
automatic appending of null character by the system.
• In Java, there are three classes that can create strings
Introduction •
and process them with nearly similar methods.
(i) class String
• (ii) class StringBuffer
• (iii) class StringBuilder
• All the three classes are part of java.lang package.
Overview of Three String Classes
• All the three classes have several constructors that can be used for
constructing strings.
• In the case of String class, an object may be created as
• String str1 = “abcd”;
Overview of Three String Classes
• The aforementioned two declarations are equivalent to the
following:
• char s1 [] = {‘a’, ‘b’, ‘c’, ‘d’};
• char s2 [] = {‘B’, ‘e’, ‘l’, ‘l’};
Storage of Strings
• The objects of class String have a special storage facility, which is
not available to objects of other classes or to objects of any other
class.
• The memory allocated to a Java program is divided into two
segments:
• (i) Stack
• (ii) Heap
Storage of Strings
• The variables are stored on heap, whereas the program is stored on
stack.
• Within the heap, there is a memory segment called ‘String constant
pool’.
• The String class objects can be created in two different ways:
String strx = “abcd”;
String strz = new String(“abcd”);
Example
public class Test {
public static void main(String[] args) throws Exception{
// TODO code application logic here
String str1="abcd";
String str2="abcd";
String str3=new String("Welcome");
String str4=new String("Welcome");
String str5=new String();
String str6="";
System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str3==str4);//it will compare reference
System.out.println(str5==str6);
System.out.println(str1.equalsIgnoreCase(str2));
System.out.println(str3.equalsIgnoreCase(str4));
System.out.println(str5.equals(str6));
}
Immutability
• The string objects created by class String are immutable.
• By immutable implies that once an object is created, its value or
contents cannot be changed.
• Neither the characters in the String object once created nor their case
(upper or lower) can be changed.
• New String objects can always be created and assigned to older String
object references.
• Thus, when you change the content of a string by defining a new string,
the old and new remain in the memory.
• The immutable objects are thread safe and so are the String objects.
Immutability
• The objects created by class StringBuffer are mutable.
• These are stored on the heap segment of memory outside the String
constant pool.
• The contents of StringBuffer strings may be changed without creating
new objects.
• The methods of StringBuffer are synchronized, and hence, they are
thread safe.
Immutability
• The objects of class StringBuilder are also mutable but are not thread
safe.
• The operations are fast as compared to StringBuffer and there is no
memory loss as is the case with String class.
• The class StringBuilder has the same methods as the class
StringBuffer.
• Therefore, if multithreads are not being used, then StringBuilder class
should be used to avoid memory loss.
Properties of String, StringBuffer, and
StringBuilder objects
Interface CharSequence
• It is an interface in java.lang package.
• It is implemented by several classes including the classes String,
• StringBuffer, and StringBuilder.
• It has the following four methods.
(i) charcharAt(int index): The method returns character value at specified
• index value.
• (ii) int length(): This method returns the length of this (invoking) character
• sequence.
• (iii) CharSequence subsequence(int startIndex, endIndex): The method returns a subsequence
from start index to end index of this sequence. Throws IndexOutOfBoundsException.
(iv)String toString(): The method returns a string containing characters of
• the sequence in the same.
Program Example
Class String
• The class String is used to represent strings in Java. It is declared as
public final class String
extends Object
implements serializable, comparable<String>, charSequence

• The String class is final, it cannot be extended.


Program Example
Constructors of Class String
Following are the constructors of class String:
1. String()
This constructor creates a string without any characters. See the
following examples.
String str = new String();
String str1 = “”;
2. String (byte [] barray)
It constructs a new string by decoding the specified byte[] barray by
using a computer’s default character set. The following code
constructs str2 = “ABCDE”.
byte []bray = new byte[]{65, 66, 67, 68, 69};
String str2 = new String(bray);
Constructors of Class String
3. String (byte [] barray, Charset specifiedset)
It constructs a new string by decoding the specified byte array (bray)
by using specified character set.
• Some of the Charsets supported by Java are UTF8, UTF16, UTF32, and ASCII.
• These may be written in lower case such as utf8, utf16, utf32, and ascii.
4. String(byte[] bray, int offset, int length, String charsetName)
The constructor constructs String object by decoding the specified
part of byte array using specified Charset.
For example
String str4 = new String(bray,1, 3, “ascii”);
Constructors of Class String
5. String (byte[] barray, string charsetName}
The constructor constructs a string by decoding the byte array using
specified Charset.
String str3 = new String(bray, “UTF8”);
• The method throws UnsupportedEncodingException if the given
charset is not supported.
Program Example
Methods for Extracting Characters from
Strings
Methods for Extracting Characters from
Strings
The signatures of the first two methods are as:
1. char charAt (int n), where n is a positive number, which gives the
location of a character in a string.
It returns the character at the specified index location.
Thus, in String ‘Delhi’ the index value of ‘D’ is 0, index value of ‘e’
is 1, ‘h’ is 3, and so on.
Methods for Extracting Characters from
Strings
2. void getChars (int SourceStartindex, int SourceEndindex, char
targetarray[], int targetindexstart)
• This method takes characters from a string and deposits them in
another string.
• int SourceStartindex and int SourceEndindex relate to the source
string.
• char targetarray[] relates to the array that receives the string
characters. The int targetindexstart is the index value of target array.
Program Example
Methods for Comparison of Strings
Difference between == and Method Equals()
The operator == simply compares the references. E.g.
if (str1==str2)

The contents are compared by the method equals() as


if (str1.equals(str3))
Program Example
Program Example
Methods for Modifying Strings
The ways to modify strings are as follows:
1. Define a new string.
2. Create a new string out of substring of an existing string.
3. Create a new string by adding two or more substrings.
4. Create a new string by replacing a substring of an existing string.
5. Create a new string by trimming the existing string.
Methods for Modifying Strings
Program Example
Methods for Searching Strings
indexOf()
(i)Int indexOf(int character/substring)—searches for the first
occurrence of a specified character in the string.
(ii)int indexOf(int character/substring, int index)—searches for the
first occurrence of a specified character or substring and the
search starts from the specified index value, that is, the second
argument.
Program Example
Data Conversion and Miscellaneous
Methods
Program Example
Class StringBuffer
It defines the strings that can be modified as well as the number of
characters that may be changed, replaced by another, a string that may
be appended, etc.
• The strings are also thread safe. For the strings created by class StringBuffer, the
compiler allocates extra capacity for 16 more characters so that small modifications
do not involve relocation of the string.

The class is declared as follows:


public final class StringBuffer
extends Object
implements Serializable, CharSequence
Constructors of Class Stringbuffer
Methods of Class Stringbuffer
public class Test {
public static void main(String[] args) throws Exception{
// TODO code application logic here
StringBuffer str=new StringBuffer("Learn Java Programming");
System.out.println("String Buffer: "+str);
System.out.println("length: "+str.length()); str.replace(2, 4, "in");
System.out.println("String Buffer: "+str); System.out.println(str);
str.delete(2, 4);
str.setLength(10);
System.out.println(str);
System.out.println("String Buffer new Length: "+str.length()); StringBuffer str1=new StringBuffer("Learn Java");
System.out.println("new String is: "+str); StringBuffer str2=str1;
System.out.println("character at 3rd index: "+str.charAt(3)); System.out.println(str1);
System.out.println(str2);
str.setCharAt(3, 'r');
str1.replace(0, 0, "E");
System.out.println("String Buffer "+str); System.out.println(str1);
System.out.println(str.reverse()); System.out.println(str2);
str.insert(5, "Complete the Learning"); }
}
System.out.println(str);
Class StringBuilder
The StringBuilder class is the subclass of Object in java.lang
package.
This class is used for creating and modifying strings.
Its declaration is as follows:
public final class StringBuilder extends Object
implements Serializable, CharSequence
Constructors of Class StringBuilder
The four constructors of the class are described as follows:

1.StringBuilder()—Creates a StringBuilder object with no characters but


with initial capacity of 16 characters.
2. StringBuilder(CharSequence chSeq)—Creates a StringBuilder object with
characters as specified in CharSequence chSeq.
3.StringBuilder(int capacity)—Creates a StringBuilder object with specified
capacity. It throws NegativeArraySizeException.
4.StringBuilder(String str)—Creates a StringBuilder object initialized with
contents of a specified string. It throws NullPointException if str is null.
Methods of Class StringBuilder
Performance: StringBuffer and StringBuilder
IO Streams
• We have stack area and heap area.
• Java program interact with the various resources in a way to transfer
the data.
• From some devices it might be taking input e.g. keyboard to the
program,
• From the file also it may sending the data to the file and from the file
• Stream is flow of data, data may flow from data to program or from
program to data
Issues with Streams
• Buffer: Consider one resource in the program, where data is being
sent by the program to the resource but there may be mismatch of
the speed from which data is being sent by the program and the data
received by the resource.
• What if the speed is not matched then there will be wastage of data.
• In order to maintain the speed between the two we need buffer. So
the program will send the data to buffer and then the data will be
picked from the buffer.
• Buffer is memory area that hold the data for some time to bring the
compatibility between the device. Example: buffering of video.
• Data flow in program, String S=“john” then first j then o then h and n will be
moved byte by byte.
• An object or data will be broken into bytes and then it will be sent bytewise
• For streams java has lots of built-in classes for streams
• Broadly java provides two types of streams: byte stream as we discussed that
data flow in byte wise so byte stream class. And another is character stream
classes.
• Difference is byte means 1 byte but in java character takes 2 byte.
• Whether it’s a byte or character data will flow in terms of byte only.
• Since java supports Unicode for character stream and that is why it has
separate set of classes of character stream.
Byte Stream
• Input stream : whatever data flow is coming inside java program is
input stream
• Output stream: whatever data flow from java program is output
stream.
• Similarly for character stream we have Reader class and Writer class
Input stream methods
• Input stream:
• int read(): method reads the next byte of the data from the the input stream and
returns int in the range of 0 to 255. If no byte is available because the end of the
stream has been reached, the returned value is -1.
• int read(byte[] b): if you have collection of byte or array of bytes, so we can ask read()
method to read byte
• int read(byte[] b, int off, int len): it reads character into a portion of the array.
• int available(): it tells about how many bytes are available to read.
• long skip(long n): to skip byte that you do not want to read
• void mark(int limit): It is used for marking the present position in a stream.
• void reset(): It repositions the stream at a position the mark method was last called on this
input stream.
• boolean markSupported(): It is used to test the input stream support for the mark and reset
method.
• void close(): It closes the input stream and releases any of the system resources associated
with the stream.
Output Stream Class
• Void write(int b): This method writes the specified byte to the stream.
• Void write(byte[] b): This method writes the specified byte array to
the stream.
• Void write(byte[] b, int off, int len)
•write(char[] cbuf): This method writes the specified character array to
the stream.
• Void flush()
• Void close()
• Java.lang.Object
• Java.io.InputStream
• Java.io.FileInputStream
• Java.io.ObjectInputStream
• Java.io.SequenceInputStream
• Java.io.StringBufferInputStream
• Java.io.FilterInputStream
• Java.io.BufferedInputStream
• Java.io.DataInputStream
• Java.io.PushbackInputStream
Byte type of data
• Object
• OutputStream
• ByteArrayOutputStream: Creates a new byte array output stream with the initial capacity of 32 bytes,
though its size increases if necessary.
• FileOutputStream: Creates a file output stream to write to the file represented by the specified File
object. • FilterInputStream
• FilterOutputStream • BufferedInputStream
• BufferedOutputStream • DataInputStream
• DataOutputStream • LineNumberInputStream
• PrintStream • PushBackInputStream
• ObjectOutputStream • ObjectInputStream
• PipedOutputStream • PipedInputStream
• InputStream • SequenceInputStream
• ByteArrayInputStream • StringBufferInputStream
• FileInputStream
Character type of data
• Object
• Writer • Reader
• BufferedReader
• BufferedWriter. • BufferedInputStream
• charArrayWriter. • StringReader
• OutputStreamWriter • InputStreamReader
• FileWriter • PushbackInputStream
• PipedReader
• FilterWriter • FilterReader
• PipedWriter • LineNumberInputStream
• PrintWriter • FileReader
• StringWriter
Java.io classes
• Java.lang.Object
• Java.io.InputStream
• Java.io.ByteArrayInputStream
• Java.io.FileInputStream
• Java.io.ObjectInputStream
• Java.io.PipedInputStream
• Java.io.SequenceInputStream
• Java.io.StringBufferInputStream
• Java.io.FilterInputStream
• Java.io.BufferedInputStream
• Java.io.DataInputStream
• Java.io.PushbackInputStream
FileOutputStream
• Using fileOutputStream we will create Test.txt in MyJava folder. In the same
program I will use fileInputStream to read the content of the file

Test

Read the content


Test.txt

FileOutputStream fos FileInputStream fis

• The utilization of fileOutputStream for writing the data in a file and


FileInputStream for reading the data from a file.
• FileReader and FileWriter can also be used for the same but most
common are streams because computers works in bytes, so
FileInputStream and FileOutputStream will be used
Example
catch(IOException e)
import java.io.FileOutputStream; {
import java.io.FileNotFoundException; System.out.println(e);
import java.io.IOException; }
}
public class Test {
}
public static void main(String[] args) {
try
{
FileOutputStream fos=new FileOutputStream("C:\\Users\\richa\\Documents\\
NetBeansProjects\\Test\\Test.txt");
String str="Learning Java";
fos.write(str.getBytes());
fos.close();
}
catch(FileNotFoundException e)
{
System.out.println(e);
}
Another way
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; catch(FileNotFoundException e)
public class Test { {
System.out.println(e);
public static void main(String[] args) {
}
try { catch(IOException e)
FileOutputStream fos=new FileOutputStream {
("C:\\Users\\richa\\Documents\\NetBeansProjects\\Test\\Test.txt"); System.out.println(e);
String str="Learning Java"; }
byte b[]=str.getBytes();//this way we got all the bytes..all the bytes in the array b}
//writing all the bytes one by one in a file by using a loop
for(byte x:b) }
{
fos.write(x);
}
fos.close();
}
Offset example using FileOutputStream.Write
catch(FileNotFoundException e)
import java.io.FileNotFoundException; {
import java.io.FileOutputStream; System.out.println(e);
import java.io.IOException; }
catch(IOException e)
public class Test { {
public static void main(String[] args) { System.out.println(e);
try }
{ }
}
FileOutputStream fos=new FileOutputStream
("C:\\Users\\richa\\Documents\\NetBeansProjects\\Test\\Test.txt");
String str="Learn Java Programming";
byte b[]=str.getBytes();//this way we got all the bytes..all the bytes in the array b
//writing all the bytes one by one in a file by using a loop
fos.write(b, 6, str.length()-6);//in case I want to copy only java programming
fos.close();
}
Try with resources
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args) throws Exception
{
try (FileOutputStream fos = new FileOutputStream("C:\\Users\\richa\\Documents\\NetBeansProjects\\Test\\Test.txt"))
{
String str="Learn Java Programming";
byte b[]=str.getBytes();
fos.write(b);
}
}
}
FileInputStream
import java.io.FileInputStream;
public class Test {
public static void main(String[] args) throws Exception{
try (FileInputStream fis = new FileInputStream("C:\\Users\\richa\\Documents\\NetBeansProjects\\
Test\\Test.txt")) {
byte b[]=new byte[fis.available()];//available tells us that how many bytes are available to read
//so we are creating a byte array
fis.read(b);
String str=new String(b);
System.out.println(str);
}
}
}
• In the previous example: from the file it is coming inside a byte array
and we are reading it. From the byte array we are making it as string
and we are printing it. This is how we can read the data from a file
inputstream.
• In the next example we are reading the file letter by letter. So we took
an integer variable and we will read a file letter by letter and print it.
Do while loop uses fileInputStream to read the file and put it in x. It
will read a code and keep it in integer variable and print it by
converting it in x.
• It will be read until the end of the file.
try{
FileOutputStream fos=new FileOutputStream("C:\\
Users\\richa\\Desktop\\BIT\\Course Related\\SP-2024\\
OOPDP - Lab\\source.txt");
String str="Welcome to the java programming";
import java.io.FileInputStream; byte b[]=str.getBytes();
import java.io.FileOutputStream; fos.write(b);
fos=new FileOutputStream("C:\\Users\\richa\\Desktop\\
import java.io.IOException; BIT\\Course Related\\SP-2024\\OOPDP - Lab\\source1.txt");
import java.io.FileNotFoundException; String str1="The array in the string and file handling is an
import java.io.*; important topic";
byte b1[]=str1.getBytes();
public class File {

/**
* @param args the command line arguments
*/
public static void main(String[] args){
// TODO code application logic here
fos.write(b1);
fos.close();
FileInputStream fis=new FileInputStream("C:\\Users\\richa\\Desktop\\BIT\\Course Related\\SP-2024\\OOPDP -
Lab\\source.txt");
int x;
while((x=fis.read())!=-1)
{ catch(FileNotFoundException e)
System.out.println((char)x); {
} System.out.println(e);
System.out.println("Second file starts here"); }
fis=new FileInputStream("C:\\Users\\richa\\Desktop\\BIT\\Course Related\\SP-2024\\OOPDPcatch(IOException
- Lab\\ e)
source1.txt"); {
byte b2[]=new byte[fis.available()]; System.out.println(e);
fis.read(b2); }
}
String str2=new String(b2);
System.out.println(str2);
}
}
Read the file from a file letter by letter
import java.io.FileInputStream;
public class Test
{
public static void main(String[] args) throws Exception
{
try (FileInputStream fis = new FileInputStream("C:\\Users\\richa\\Documents\\NetBeansProjects\\Test\\Test.txt"))
{
int x;
while((x=fis.read())!=-1)
System.out.print((char)x);
}
}
}
Using FileReader
import java.io.FileInputStream;
public class Test
{
public static void main(String[] args) throws Exception
{
try (FileReader fis = new FileReader("C:\\Users\\richa\\Documents\\NetBeansProjects\\Test\\Test.txt"))
{
int x;
while((x=fis.read())!=-1)
System.out.print((char)x);
}
}
}
Using FileWriter
import java.io.FileWriter;
import java.io.IOException;
public class Test
{
public static void main(String[] args) throws Exception
{
// TODO code application logic here
try (FileWriter fos = new FileWriter("C:\\Users\\richa\\Documents\\NetBeansProjects\\Test\\Test.txt"))
{
String str="Learn Java Programming using File Writer";
fos.write(str);
}
}
}
Practice Problem
• Consider there are two files named source.txt and destination.txt
read the file and write them into another file
• Using FileInputStream open the file named source.txt and
FileOutputStream opening a file named destination.txt. When we are
using FileInputStream file must be in the mentioned path otherwise it
will throw exception FileNotFound.
• Using loop we are reading a file using FileInputStream and read and
store them until it will reach to the end of file
Copying content of one file into another
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
public class Test {
public static void main(String[] args) throws Exception{
FileInputStream fis=new FileInputStream("C:\\Users\\richa\\Documents\\NetBeansProjects\\Test\\source.txt");
FileOutputStream fos=new FileOutputStream("C:\\Users\\richa\\Documents\\NetBeansProjects\\Test\\
dest.txt");
int b;
while((b=fis.read())!=-1)
{
fos.write(b);
}
fis.close();
fos.close();
}
}
Practice Problem2: Combining the two files
into one
• sequenceInputStream will help to do the needful
• Sequentially read the file from source files and write it down in the
destination
Combining two files into another file
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.SequenceInputStream;
public class Test {
public static void main(String[] args) throws Exception{
FileInputStream fis=new FileInputStream("C:\\Users\\richa\\Documents\\NetBeansProjects\\Test\\source1.txt");
FileInputStream fis2=new FileInputStream("C:\\Users\\richa\\Documents\\NetBeansProjects\\Test\\source2.txt");
FileOutputStream fos=new FileOutputStream("C:\\Users\\richa\\Documents\\NetBeansProjects\\Test\\
destination1.txt");
SequenceInputStream s=new SequenceInputStream(fis,fis2);
int b;
while((b=s.read())!=-1)
{
fos.write(b);
}
s.close();
fis.close();
fis2.close();
fos.close() }
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.*;
public class File {
public static void main(String[] args){
// TODO code application logic here
try{
FileInputStream fis=new FileInputStream("C:\\Users\\richa\\Desktop\\BIT\\Course Related\\SP-2024\\OOPDP - Lab\\
source.txt");
FileInputStream fis2=new FileInputStream("C:\\Users\\richa\\Desktop\\BIT\\Course Related\\SP-2024\\OOPDP -
Lab\\source1.txt");
FileOutputStream fos=new FileOutputStream("C:\\Users\\richa\\Desktop\\BIT\\Course Related\\SP-2024\\OOPDP -
Lab\\destination.txt");
SequenceInputStream s=new SequenceInputStream(fis, fis2);
catch(FileNotFoundException e)
{
System.out.println(e);
}
int b;
catch(IOException e)
while((b=s.read())!=-1) {
{ System.out.println(e);
fos.write(b); }
} }
s.close();
}
fis.close();
fis2=new FileInputStream("C:\\Users\\richa\\Desktop\\BIT\\Course Related\\SP-2024\\OOPDP - Lab\\
destination.txt");
byte b1[]=new byte[fis2.available()];
fis2.read(b1);
String str=new String(b1);
System.out.println(str);
}
ByteStreams and CharArrayReader
• Here source of data is not a file, it is an array
• ByteArrayInputStream will help to read the data from array of bytes.
The array may have integer or character
• ByteArrayOutputStream will help to modify the array and to write the
content in the array.
• This array will be treated like a stream so we will use it using
ByteArrayInputStream
Reading one byte at a time
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception{
byte b[]={'a','b','c','d'};
ByteArrayInputStream bis=new ByteArrayInputStream(b);
//to read the data from the stream
int x;
while((x=bis.read())!=-1)
{
System.out.println((char)x);
}
bis.close();
}
}
Reading all bytes at once
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception
{
byte b[]={'a','b','c','d'};
ByteArrayInputStream bis=new ByteArrayInputStream(b);
//to read the data from the stream
//creating a string and pushing all byte at once
String str=new String(bis.readAllBytes());
System.out.println(str);
bis.close();
}
}
To check whether it support mark and reset
• Instead of printing the string it will print true or false depending on
whether it support mark or not.
• Since its an array where we are using mark so it can come back to the
previous pointer whereas in file the pointer always moves forward so
we can not use mark with files.
byteArrayOutputStream
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception{
ByteArrayOutputStream bos=new ByteArrayOutputStream(20);
bos.write('a');
bos.write('b');
bos.write('c');
bos.write('d');
//the alphabets are stored inside the array of bytes
//in order to see those letter the method bos.toByteArray
byte b[]=bos.toByteArray();//from the stream you are getting bytes of array and store them in array of bytes
for(byte x:b)
System.out.println(x);
//since we are printing byte value so it will give ASCII
bos.close();
}
Typecasting the bytes into character will print
the character of array
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception{
ByteArrayOutputStream bos=new ByteArrayOutputStream(20);
bos.write('a');
bos.write('b');
bos.write('c');
bos.write('d');
//the alphabets are stored inside the array of bytes
//in order to see those letter the method bos.toByteArray
byte b[]=bos.toByteArray();//from the stream you are getting bytes of array and store them in array of bytes
for(byte x:b)
System.out.println((char)x);
//since we are printing byte value so it will give ASCII
bos.close();
}
}
charArrayReader Example
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception{
char c[]={'a','b','c','d','e'};
CharArrayReader c1=new CharArrayReader(c);
int x;
while((x=c1.read())!=-1)
System.out.print((char)x);
c1.close();
}
}
BufferedReader and Write
• Over fileInputStream we will attach bufferedInputStream.
• Buffer is a temporary memory area which will hold the data so that
we can utilize the data smoothly when there is speed mismatch
between the input and output
• The data will come inside the fileInputStream
• For writing the data into the file we require outputStream and over
this we will attach BufferedOutputStream.

Files fis bis Program Program bos fos Files


• There is no such difference that you can observe for fileInputStream
and BufferedInputStream. Like the same way you access
fileInputStream you are accessing BufferedInputStream. There is no
extra method is present. But when you are using it definitely there is
difference in performance
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception{
// TODO code application logic here
FileInputStream fis=new FileInputStream("C:\\Users\\richa\\Documents\\NetBeansProjects\\Test\\
source.txt");
BufferedInputStream bis=new BufferedInputStream(fis);
int x;
while((x=bis.read())!=-1)
{
System.out.print((char)x);
}
}
}
Benefit of BufferedStream
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception{
// TODO code application logic here
FileInputStream fis=new FileInputStream("C:\\Users\\richa\\Documents\\
NetBeansProjects\\Test\\source.txt");
BufferedInputStream bis=new BufferedInputStream(fis);
//benefit of BufferedInputStream
System.out.println("File: "+fis.markSupported());
System.out.println("Buffer: "+bis.markSupported());
}
}
• BufferedStream can work with markSupported, it can keep data in
buffer but the same does not go with FileStream, with FileStream it
works as tapes which moves only forward and not in backward
direction.
Mark and reset example
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception{
// TODO code application logic here
FileInputStream fis=new FileInputStream("C:\\Users\\richa\\Documents\\NetBeansProjects\\Test\\
source.txt");
BufferedInputStream bis=new BufferedInputStream(fis);
//benefit of BufferedInputStream
System.out.print((char)bis.read());
System.out.print((char)bis.read());
System.out.print((char)bis.read());
bis.mark(10);
System.out.print((char)bis.read());
System.out.print((char)bis.read());
bis.reset();
System.out.print((char)bis.read());
System.out.print((char)bis.read());
}
}

You might also like