2 - IO - File Handling-STRING HANDLING (Unit-2)
2 - IO - File Handling-STRING HANDLING (Unit-2)
• It's called a stream because it is like a stream of water that continues to flow.
• Streams are sequence of data(composed of bytes) that are read from source &
written to destination.
• An input stream is used to read data from source & an output stream is write
data to the destination.
• There are 3 streams created for us automatically that are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Code to print output and an error message to the console :
• defined by using two abstract class at the top of hierarchy, they are InputStream and
OutputStream.
• These two abstract classes have several concrete classes that handle various devices
such as disk files, network connection etc.
Some important Byte stream classes
DataOutputStream An output stream that contain method for writing java standard data type
These classes define several key methods. Two most important are :
read() : reads byte of data.
write() : Writes byte of data.
(2) Character Stream Classes
• It is also defined by using two abstract class at the top of hierarchy, they are
Reader & Writer.
• Character stream classification:
• These two abstract classes have several concrete classes that handle unicode character.
Stream class Description
BufferedReader Handles buffered input stream.
Some important Character BufferedWriter Handles buffered output stream.
stream classes FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
Reading Characters :
• read() method is used with BufferedReader object to read characters.
• As this function returns integer type value, we need to use typecasting to convert it into char type.
• int read() throws IOException class CharRead {
public static void main( String args[]) {
BufferedReader br = new Bufferedreader(new
InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
} }
Reading Strings :
• To read string we have to use readLine() function with BufferedReader class's object.
• String readLine() throws IOException
import java.io.*;
class MyInput {
public static void main(String[] args) {
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
} }
Program to read from a file using BufferedReader class :
import java. Io *;
class ReadTest {
public static void main(String[] args) {
try {
File fl = new File("d:\myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null) {
System.out.println(str); }
br.close();
fl.close();
}
catch(IOException e) {
e.printStackTrace();
} } }
Program to write to a File using FileWriter class :
import java. Io *;
class WriteTest {
public static void main(String[] args) {
try {
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
} }
Java Serialization and Deserialization
• Java provides Serializable API encapsulated under java.io package for serializing
and deserializing objects
Marker interface
• It is a special interface without any field and method.
• It is used to inform compiler that the class implementing it has some special
behaviour or meaning.
• Some example of Marker interface are :
• java.io.serializable
• java.lang.Cloneable
• java.rmi.Remote
• java.util.RandomAccess
• However marker interfaces have been deprecated since Java 5, they were
replaced by Annotations.
• Annotations play the exact same role as marker interfaces did before.
transient Keyword
• While serializing an object, if we don't want certain data member of the object to be serialized
we can mention it transient.
• transient keyword will prevent that data member from being serialized.
char[] ch={'j','a','v','a','t','p',’r',’o',’g',’r’,’a’,’m’};
String s=new String(ch);
is same as: String s="javatprogram";
• String class methods: Used to perform operations on strings such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
• The StringBuffer and StringBuilder classes have the same methods with one
• By the help of these methods, we can perform operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc.
3 ways:
• public boolean equals(Object another) compares this string to the specified object.
Example: It compares the content of the strings. It will return true if string matches, else returns false.(But match the
case). To ignore the case, use “equalsIgnoreCase())
class Teststringcomparison2{
public static void main(String args[]){
String s1="Kunj";
String s2="KUNJ";
System.out.println("s1.equals(s2)=>>"+s1.equals(s2));//false
System.out.println("s1.equalsIgnoreCase(s2)=>>"+s1.equalsIgnoreCase(s2));//true
} }
(B-2) Using == operator
compares two object references to check whether they refer to same instance.
This also, will return true on successful match else returns false.
class Test3{
public static void main(String args[]){
String s1="Kunj";
String s2="Kunj";
String s3=new String("Kunj");
System.out.println("s1==s2=>>"+(s1==s2));//true (because both refer to same instance)
System.out.println("s1==s3=>>"+(s1==s3));//false(because s3 refers to instance created in nonpool)
} }
We can get substring from the given string object by one of the two methods:
Example :
public class TestSubstring{
public static void main(String args[]){
String s="Aviral Maitrey";
System.out.println(s.substring(7)); //Maitrey
System.out.println(s.substring(0,6)); // Aviral
}
}
(D) String toUpperCase() and toLowerCase() method
toUpperCase() : converts given string into uppercase letter
toLowerCase() : converts given string into lowercase letter.
Example: public class TestCase{
public static void main(String args[]){
String s="Abhineet";
System.out.println("s.toUpperCase()=>>"+s.toUpperCase()); //ABHINEET
System.out.println("s.toLowerCase()=>>"+s.toLowerCase()); //abhineet
System.out.println("Original String=>>"+s); //Abhineet(no change in
original)
} }
(E) String trim() method
eliminates white spaces before and after string
Example:
public class TestTrim
{
public static void main(String args[]){
String s=" Abhineet";
System.out.println("Actual string=>>"+s); // Abhineet(with whitespace)
System.out.println("Using trim=>>"+s.trim()); //Abhineet(no whitespace)
}
}
(F) startsWith() and endsWith() method
startsWith(): check whether the given string starts with given prefix or not and returns true when prefix matches the string else it returns
false.
endsWith(): check whether the string ends with the given suffix or not and returns true when suffix matches the string else it returns false.
Example: public class TestStartEnd{
public static void main(String args[]){
String s="Abhineet";
System.out.println("Given String is=>"+s);
System.out.println(s.startsWith("Se")); //false
System.out.println(s.endsWith("t")); //true
System.out.println(s.startsWith("Ab")); //true
System.out.println(s.startsWith("ab")); //false
System.out.println(s.endsWith("T")); //false
} }
Example:
used to create mutable (modifiable) string. It is same as String class except it is mutable i.e. it can be changed.
It is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order.
StringBuffer and StringBuilder classes are used for creating mutable string.
a) StringBuffer append() method
The append() method concatenates the given argument with provided string.
class SBconcat{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java"); //now original string is changed
System.out.println(sb); //prints Hello Java
}
}
b) insert() method
inserts the given string with this string at the given position.
class SBinsert{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(2,"Java"); //now original string is changed
System.out.println(sb); //prints HeJavallo
}
}
c) StringBuffer replace() method
replaces the given string from the specified beginIndex and endIndex.
class SBreplace{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo
}
}
class Sbdelete
{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb); //prints Hlo
}
}
e) StringBuffer reverse() method
It reverses the current string. Prints from last index.
Example:
class SBreverse{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Kunj");
System.out.println("Original String:"+sb);
//sb.reverse();
System.out.println("Reversed String:"+sb.reverse()); } }
Example:
class SBcapacity{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println("Default Capacity of sb:"+sb.capacity()); //default 16
sb.append("Hello");
System.out.println("After appending Hello into sb, capacity is=>>"+sb.capacity()); //now 16
sb.append("WT is my favourite subject");
System.out.println("Appending another string into sb, capacity is=>>"+sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2
} }
StringBuilder class
StringBuilder also used for creating string object that is mutable and non synchronized. StringBuffer and StringBuilder
both are mutable but if synchronization is not required then it is recommend to use StringBuilder class.
Constructor Description
StringBuilder() creates an empty string Builder with the initial capacity of 16.
StringBuilder(String str) creates a string Builder with the specified string.
StringBuilder(int length) creates an empty string Builder with the specified capacity as length.
class SBLappend{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Important methods of StringBuilder class
Method Description
public StringBuilder append(String s) is used to append the specified string with this string. The append() method is
overloaded like append(char), append(boolean), append(int), append(float),
append(double) etc.
public StringBuilder insert(int offset, String s) is used to insert the specified string with this string 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 replace(int startIndex, int endIndex, is used to replace the string from specified startIndex and endIndex.
String str)
public StringBuilder delete(int startIndex, int endIndex) is used to delete the string from specified startIndex and endIndex.
public void ensureCapacity(int minimumCapacity) is used to ensure the capacity at least equal to the given minimum.
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number of characters.
public String substring(int beginIndex) is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, int endIndex) is used to return the substring from the specified beginIndex and endIndex.
StringTokenizer class
A class that allows us to break a string into tokens based on provided delimiter.
It is simple way to break string. It is located into java.util package.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
import java.util.StringTokenizer;
public class TestSThasmoretokens{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("My name is KUNJ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
} } }
import java.util.*;
public class TestSTnextoken{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("My,name,is,KUNJ");
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
}
}