0% found this document useful (0 votes)
3 views13 pages

String&Filehandling

Unit VI covers the String and StringBuffer classes in Java, detailing their methods and differences, as well as the File class for file handling. It explains how to create and manipulate strings, including various methods for comparison, concatenation, and modification. Additionally, it discusses stream classes for reading and writing data, including character and byte streams, and provides examples of file operations using FileWriter and FileReader.

Uploaded by

Samiksha
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)
3 views13 pages

String&Filehandling

Unit VI covers the String and StringBuffer classes in Java, detailing their methods and differences, as well as the File class for file handling. It explains how to create and manipulate strings, including various methods for comparison, concatenation, and modification. Additionally, it discusses stream classes for reading and writing data, including character and byte streams, and provides examples of file operations using FileWriter and FileReader.

Uploaded by

Samiksha
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

Unit VI : Strings, Streams and Files

6.1 String class and StringBuffer Class


6.2 Using the File class
6.3 Stream classes
6.3.1 Byte Stream classes
6.3.2 Character Stream Classes
6.4 Creation of files ,Reading/Writing characters and bytes, Handling primitive data types
6.5 Random Access files

String Class: The [Link] class provides a lot of methods to work on string. By the
help of these methods, we can perform operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc. Strings, which are widely used in Java
programming, are a sequence of characters. In Java programming language, strings are
treated as objects

Creating a String
There are two ways to create a String in Java

1. String literal :

Example: String s1=”hello”;

2. Using new keyword

Example: String s2=new Stirng(”hello”);

String Methods :

1. char charAt(int index): It returns the character at the specified index. Specified index
value should be between 0 to length() -1 both inclusive.
2. boolean equals(Object obj): Compares the string with the specified string and returns
true if both matches else false.
3. boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t
consider the case while comparing strings. It does a case insensitive comparison.
4. int compareTo(String string): This method compares the two strings based on the
Unicode value of each character in the strings.
5. boolean startsWith(String prefix): It tests whether the string is having specified prefix, if
yes then it returns true else false.
6. boolean endsWith(String suffix): Checks whether the string ends with the specified
suffix.
7. int indexOf(int ch): Returns the index of first occurrence of the specified character ch in
the string.
8. int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching
in the string from the specified fromIndex.
9. int lastIndexOf(int ch): It returns the last occurrence of the character ch in the string.
10. int lastIndexOf(int ch, int fromIndex): Same as lastIndexOf(int ch) method, it starts
search from fromIndex.
11. int indexOf(String str): This method returns the index of first occurrence of specified
substring str.
12. int lastindexOf(String str): Returns the index of last occurrence of string str.
13. String substring(int beginIndex): It returns the substring of the string. The substring
starts with the character at the specified index.
14. String substring(int beginIndex, int endIndex): Returns the substring. The substring
starts with character at beginIndex and ends with the character at endIndex.
15. String concat(String str): Concatenates the specified string “str” at the end of the string.
16. String replace(char oldChar, char newChar): It returns the new updated string after
changing all the occurrences of oldChar with the newChar.
17. boolean contains(CharSequence s): It checks whether the string contains the specified
sequence of char values. If yes then it returns true else false. It throws
NullPointerException of ‘s’ is null.
18. String toUpperCase(): Converts the string to upper case string .
19. String toLowerCase():Converts the string to lower case string .
20. String[] split(String regex): It splits the string and returns the array of substrings that
matches the given regular expression.
21. String trim(): Returns the substring after omitting leading and trailing white spaces from
the original string.
22. char[] toCharArray(): Converts the string to a character array.
23. void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): It copies the
characters of srcarray to the dest array. Only the specified range is being
copied(srcBegin to srcEnd) to the dest subarray(starting fromdestBegin).
24. static String valueOf(): This method returns a string representation of passed arguments
such as int, long, float, double, char and char array.
25. byte[] getBytes(String charsetName): It converts the String into sequence of bytes using
the specified charset encoding and returns the array of resulted bytes.
26. byte[] getBytes(): This method is similar to the above method it just uses the default
charset encoding for converting the string into sequence of bytes.
27. int length(): It returns the length of a String.

StringBuffer Class:

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class
in java is same as String class except it is mutable i.e. it can be changed.

Constructors:

1) StringBuffer( ): It reserves room for 16 characters without reallocation.


StringBuffer st=new StringBuffer();
2) StringBuffer( int size)It accepts an integer argument that explicitly sets the size of
the buffer.
StringBuffer st=new StringBuffer(20);
3) StringBuffer(String str): It accepts a String argument that sets the initial contents of
the StringBuffer object and reserves room for 16 more characters without reallocation.
StringBuffer st=new StringBuffer(“welcome”);

Methods :

[Link]. Method & Description

1 StringBuffer append(char c)
This method appends the string representation of the char
argument to this sequence.

2 StringBuffer append(char[] str)


This method appends the string representation of the char array
argument to this sequence.

3 StringBuffer append(double d)
This method appends the string representation of the double
argument to this sequence.

4 StringBuffer append(float f)
This method appends the string representation of the float
argument to this sequence.

5 StringBuffer append(int i)
This method appends the string representation of the int argument
to this sequence.

6 StringBuffer append(long lng)


This method appends the string representation of the long
argument to this sequence.

7 StringBuffer append(Object obj)


This method appends the string representation of the Object
argument.

8 StringBuffer append(String str)


This method appends the specified string to this character
sequence.

9 StringBuffer append(StringBuffer sb)


This method appends the specified StringBuffer to this sequence.

10 int capacity()
This method returns the current capacity.

11 char charAt(int index)


This method returns the char value in this sequence at the
specified index.

12 StringBuffer delete(int start, int end)


This method removes the characters in a substring of this
sequence.

13 StringBuffer deleteCharAt(int index)


This method removes the char at the specified position in this
sequence

14 void ensureCapacity(int minimumCapacity)


This method ensures that the capacity is at least equal to the
specified minimum.

15 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)


This method characters are copied from this sequence into the
destination character array dst.
16 int indexOf(String str)
This method returns the index within this string of the first
occurrence of the specified substring.

17 int indexOf(String str, int fromIndex)


This method returns the index within this string of the first
occurrence of the specified substring, starting at the specified
index.

18 StringBuffer insert(int offset, String str)


This method inserts the string into this character sequence.

19 int lastIndexOf(String str)


This method returns the index within this string of the rightmost
occurrence of the specified substring.

20 int lastIndexOf(String str, int fromIndex)


This method returns the index within this string of the last
occurrence of the specified substring.

21 int length()
This method returns the length (character count).

22 StringBuffer replace(int start, int end, String str)


This method replaces the characters in a substring of this sequence
with characters in the specified String.

23 StringBuffer reverse()
This method causes this character sequence to be replaced by the
reverse of the sequence.

24 void setCharAt(int index, char ch)


The character at the specified index is set to ch.

25 void setLength(int newLength)


This method sets the length of the character sequence.

26 String substring(int start)


This method returns a new String that contains a subsequence of
characters currently contained in this character sequence

27 String substring(int start, int end)


This method returns a new String that contains a subsequence of
characters currently contained in this sequence.
28 String toString()
This method returns a string representing the data in this
sequence.

Difference Between String and StringBuffer class:

String StringBuffer

The length of the String object is The length of the StringBuffer can be

fixed. increased.

String object is immutable StringBuffer object is mutable.

It is slower during concatenation. It is faster during concatenation .

Consumes more memory. Consumes less memory.

String constant pool. Heap Memory.

File Class:

The File class is Java’s representation of a file or directory path name. Because file and
directory names have different formats on different platforms, a simple string is not adequate
to name them. The File class contains several methods for working with the path name,
deleting and renaming files, creating new directories, listing the contents of a directory, and
determining several common attributes of files and directories.

 It is an abstract representation of file and directory pathnames.


 A pathname, whether abstract or in string form can be either absolute or relative. The
parent of an abstract pathname may be obtained by invoking the getParent() method of
this class.
 First of all, we should create the File class object by passing the filename or directory
name to it. A file system may implement restrictions to certain operations on the actual
file-system object, such as reading, writing, and executing. These restrictions are
collectively known as access permissions.
 Instances of the File class are immutable; that is, once created, the abstract pathname
represented by a File object will never change.
How to create a File Object?
A File object is created by passing in a String that represents the name of a file, or a String
or another File object.
Example: File f1=new File(“/usr/local/bin/rk”);
Constructors
 File(File parent, String child) : Creates a new File instance from a parent abstract
pathname and a child pathname string.
 File(String pathname) : Creates a new File instance by converting the given pathname
string into an abstract pathname.
 File(String parent, String child) : Creates a new File instance from a parent pathname
string and a child pathname string.
 File(URI uri) : Creates a new File instance by converting the given file: URI into an
abstract pathname.
Methods
1) boolean canExecute() : Tests whether the application can execute the file denoted by

this abstract pathname.


2) boolean canRead() : Tests whether the application can read the file denoted by this
abstract pathname.
3) boolean canWrite() : Tests whether the application can modify the file denoted by
this abstract pathname.
4) boolean createNewFile() : Atomically creates a new, empty file named by this
abstract pathname .
5) boolean delete() : Deletes the file or directory denoted by this abstract pathname.
6) boolean equals(Object obj) : Tests this abstract pathname for equality with the given
object.
7) boolean exists() : Tests whether the file or directory denoted by this abstract
pathname exists.
8) String getAbsolutePath() : Returns the absolute pathname string of this abstract
pathname.
9) String getName() : Returns the name of the file or directory denoted by this abstract
pathname.
10) String getParent() : Returns the pathname string of this abstract pathname’s parent.
11) String getPath() : Converts this abstract pathname into a pathname string.
12) boolean isDirectory() : Tests whether the file denoted by this pathname is a
directory.
13) boolean isFile() : Tests whether the file denoted by this abstract pathname is a normal
file.
14) boolean isHidden() : Tests whether the file named by this abstract pathname is a
hidden file.
15) long length() : Returns the length of the file denoted by this abstract pathname.
16) String[] list() : Returns an array of strings naming the files and directories in the
directory .
17) File[] listFiles() : Returns an array of abstract pathnames denoting the files in the
directory.
18) boolean mkdir() : Creates the directory named by this abstract pathname.

Program to check if a file or directory physically exist or not.:

import [Link].*;

class fileProperty
{
public static void main(String[] args) {
//accept file name or directory name through command line args
String fname =args[0];

//pass the filename or directory name to File object


File f = new File(fname);

//apply File class methods on File object


[Link]("File name :"+[Link]());
[Link]("Path: "+[Link]());
[Link]("Absolute path:" +[Link]());
[Link]("Parent:"+[Link]());
[Link]("Exists :"+[Link]());
if([Link]())
{
[Link]("Is writeable:"+[Link]());
[Link]("Is readable"+[Link]());
[Link]("Is a directory:"+[Link]());
[Link]("File Size in bytes "+[Link]());
}
}
}

File Handling :

The [Link] package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination.
The stream in the [Link] package supports many data such as primitives, object, localized
characters, etc.

Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
 InPutStream − The InputStream is used to read data from a source.
 OutPutStream − The OutputStream is used for writing data to a destination.

In java there are two types of classes

1)CharacterStream class

2)ByteStream class

1) CharacterStream Class:

Java FileWriter and FileReader classes are used to write and read data from text files (they
are Character Stream classes).

FileWriter:
FileWriter is useful to create a file writing characters into it.

 FileWriter(File file) – This constructor constructs a FileWriter object when a file object
is given.
 FileWriter (String fileName) –This constructor constructs a FileWriter object when a file
name is given.

Methods:

 public void write (int c) throws IOException – writes a single character.


 public void write (char [] stir) throws IOException – writes an array of characters.
 public void write(String str)throws IOException – writes a string.
import [Link];
import [Link];
class CreateFile
{
public static void main(String[] args) throws IOException
{
String str = "File Handling in Java using “;
FileWriter fw=new FileWriter("text");
[Link](str);s
[Link]();
}
}

Java FileReader
Java FileReader uses for reading the data which are in the form of characters and it is done
from a ‘text’ file.
This class inherits from the InputStreamReader Class.
The constructors of this class are assuming that the default character encoding and the default
byte- are appropriate. To confirm these values by your own, construct an InputStreamReader
on a FileInputStream.
Java FileReader uses for particularly reading streams of character. For reading streams of raw
bytes, FileInputStream can use.

Constructors

 FileReader(File file) – This constructor creates a FileReader only when there is File to
read from.
 FileReader(String fileName) – This constructor creates a new FileReader.

Methods

 public int read () throws IOException – This method reads a single character and also
blocks one until another one is available, i.e. an input/output error occurs.
 public int read(char[] cbuff) throws IOException – This method reads characters into
an array. It will block until a character is available.

 public long skip(long n) throws IOException –This method skips characters and also
blocks until some characters are available, an I/O error occurs, or the end of the stream
reach.

Following program depicts how to read from the ‘text’ file using FileReader

1. import [Link];
2. import [Link];
3. import [Link];
4. class ReadFile
5. {
6. public static void main(String[] args) throws IOException
7. {
8. int ch;
9. FileReader fr=null;
10. try
11. {
12. fr = new FileReader("text");
13. }
14. catch (FileNotFoundException fe)
15. {
16. [Link]("File not found");
17. }
18. while ((ch=[Link]())!=-1)
19. [Link]((char)ch);
20. [Link]();
21. }
22. }

2) ByteStream Classes:

Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes
are descended from InputStream and OutputStream.

There are many byte stream classes. To demonstrate how byte streams work, we'll focus on
the file I/O byte streams, FileInputStream and FileOutputStream.

Example:

import [Link].*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}

RandomAccesFile :

[Link] Class provides a way to random access files using reading and
writing operations.

Constructor
Constructor Description

RandomAccessFile(File Creates a random access file stream to read from, and optionally
file, Stringmode) to write to, the file specified by the File argument.

RandomAccessFile(String name, Creates a random access file stream to read from, and optionally
String mode) to write to, a file with the specified name.

Method
Modifier Method Method
and Type
void close() It closes this random access file stream and releases any system
resources associated with the stream.

int readInt() It reads a signed 32-bit integer from this file.

String readUTF() It reads in a string from this file.

void seek(long pos) It sets the file-pointer offset, measured from the beginning of this
file, at which the next read or write occurs.

void writeDouble(double It converts the double argument to a long using the


v) doubleToLongBits method in class Double, and then writes that
long value to the file as an eight-byte quantity, high byte first.

void writeFloat(float v) It converts the float argument to an int using the floatToIntBits
method in class Float, and then writes that int value to the file as a
four-byte quantity, high byte first.

void write(int b) It writes the specified byte to this file.

int read() It reads a byte of data from this file.

long length() It returns the length of this file.

void seek(long pos) It sets the file-pointer offset, measured from the beginning of this
file, at which the next read or write occurs.

You might also like