Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

java unit-4

The Java Collections Framework provides a structured architecture for storing and manipulating groups of objects, offering various interfaces and classes for operations like searching, sorting, and deletion. It enhances development practices through reusability, quality, speed, and easier maintenance, while also introducing generics for type safety and code reusability. Key components include collections like ArrayList, Vector, and Hashtable, each with unique characteristics and use cases.

Uploaded by

rsgnr2006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

java unit-4

The Java Collections Framework provides a structured architecture for storing and manipulating groups of objects, offering various interfaces and classes for operations like searching, sorting, and deletion. It enhances development practices through reusability, quality, speed, and easier maintenance, while also introducing generics for type safety and code reusability. Key components include collections like ArrayList, Vector, and Hashtable, each with unique characteristics and use cases.

Uploaded by

rsgnr2006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Collections in Java

The Collection in Java is a framework that provides architecture to store and manipulate the
group of objects.

Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.

Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is a Framework in Java?


A framework is a set of classes and interfaces which provide a ready-made architecture. In
order to implement a new feature or a class, there is no need to define a framework.
However, an optimal object-oriented design always includes a framework with a collection
of classes such that all the classes perform the same kind of task.
Need for a Separate Collection Framework in Java
Before the Collection Framework(or before JDK 1.2) was introduced, the standard methods
for grouping Java objects (or collections) were Arrays or Vectors, or Hashtables. All of
these collections had no common interface. Therefore, though the main aim of all the
collections is the same, the implementation of all these collections was defined
independently and had no correlation among them. And also, it is very difficult for the
users to remember all the different methods, syntax, and constructors present in every
collection class.
Advantages of the Java Collection Framework
The Java Collections Framework offers significant advantages that enhance development
practices, code quality, and application performance:

1. Reusability: The framework provides a comprehensive set of common classes and


utility methods applicable across various types of collections. This feature promotes
code reusability, sparing developers the need to write duplicate code for common
operations.
2. Quality: Leveraging the Java Collections Framework elevates the quality of
programs. The components within the framework have been extensively tested and
are widely used by a vast community of developers, ensuring reliability and stability
in your applications.
3. Speed: Developers often report an increase in development speed when using the
Collections Framework. It allows them to concentrate on the core business logic of
their applications rather than on implementing generic collection functionalities, thus
speeding up the development process.
4. Maintenance: The open-source nature of the Java Collections Framework, coupled
with readily available API documentation, facilitates easier code maintenance. Code
written using the framework can be easily understood and taken over by other
developers, ensuring continuity and ease of maintenance.
5. Reduces Effort to Design New APIs: An additional benefit is the reduced necessity
for API designers and implementers to create new collection mechanisms for each
new API. They can instead rely on the standard collection interfaces provided by the
framework, streamlining the API development process and ensuring consistency
across Java applications.
Hierarchy of Collection Framework
Let's see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.

The Java Collections Framework is structured around key interfaces-Collection, List, Set,
Queue, and Map. Each tailored for specific data management tasks. Implementations like
ArrayList, HashSet, and HashMap offer practical solutions for working with these
collections, giving Java developers a versatile set of tools for efficient data handling.

o Class: A class is a blueprint from which individual objects are created. It encapsulates
data for objects through fields (attributes) and defines behavior via methods. Classes
support inheritance, allowing one class to inherit the properties and methods of
another, facilitating code reuse and polymorphism.
o Interface: An interface is a reference type in Java that can contain constants and
abstract methods (methods without a body). Interfaces specify what a class must do
but not how it does it, enforcing a set of methods that the class must implement.
Interfaces are used to achieve abstraction and multiple inheritance in Java.
Generics in Java
Generics means parameterized types. The idea is to allow a type (like Integer, String, etc.,
or user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics,
it is possible to create classes that work with different data types. An entity such as a class,
interface, or method that operates on a parameterized type is a generic entity.

Why Generics?
Generics provide a way to create reusable code components in Java, improving type safety
and readability.

Types of Java Generics:

Generic Method: Generic Java method takes a parameter and returns some value after
performing a task. It is exactly like a normal function, however, a generic method has type
parameters that are cited by actual type. This allows the generic method to be used in a
more general way. The compiler takes care of the type of safety which enables
programmers to code easily since they do not have to perform long, individual type
castings.

Generic Classes: A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than one type of
parameter, separated by a comma. The classes, which accept one or more parameters, ?are
known as parameterized classes or parameterized types.

Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects
of a generic class, we use the following syntax.

// To create an instance of generic class


BaseType <Type> obj = new BaseType <Type>()

Note: In Parameter type we can not use primitives like ‘int’,’char’ or ‘double’.

// We use < > to specify Parameter type

class Test<T, U>

T obj1; // An object of type T

U obj2; // An object of type U

Test(T obj1, U obj2)

this.obj1 = obj1;
this.obj2 = obj2;

public void print()

System.out.println(obj1);

System.out.println(obj2);

}
}
class Main
{
public static void main (String[] args)
{
Test <String, Integer> obj = new Test<String, Integer>("GfG", 15);
obj.print();
}
}
Output
GfG
15

JAVA ARRAYLIST

ArrayList in Java is a dynamic array implementation that belongs to the Java Collections
Framework. This is a big array that grows on its own as more elements are added to it.

ArrayLists come from the java.util package and are quite commonly used for their ease of use
and flexibility. They offer flexibility in that you do not need to determine the size of the
ArrayList at the time of its creation, which is similar to standard arrays in Java. So, it is much
more flexible than the traditional array. It is like the Vector in C++.

Syntax:

ArrayList list=new ArrayList();//creating old non-generic arraylist

ArrayList<string> list=new ArrayList<string>(); //generic arraylist

1. import java.util.*;
2. public class ArrayListExample1{
3. public static void main(String args[]){
4. ArrayList<string> list=new ArrayList<string>();//Creating arraylist
5. list.add("Mango");//Adding object in arraylist
6. list.add("Apple");
7. list.add("Banana");
8. list.add("Grapes");
9. //Printing the arraylist object
10. System.out.println(list);
11. }
12. }

Output:

[Mango, Apple, Banana, Grapes]

EXAMPLE 2:

1. import java.util.*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }
Output:

Ravi
Vijay
Ravi
Ajay

Java Vector

Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can
store n-number of elements in it as there is no size limit. It is a part of Java Collection
framework since Java 1.2. It is found in the java.util package and implements
the List interface, so we can use all the methods of List interface here.
It is recommended to use the Vector class in the thread-safe implementation only. If you don't
need to use the thread-safe implementation, you should use the ArrayList, the ArrayList will
perform better in such case.

It is similar to the ArrayList, but with two differences-

o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a collections
framework.

o import java.util.*;
o public class TestJavaCollection3
o {
o public static void main(String args[])
o {
o Vector<String> v=new Vector<String>();
o v.add("Ayush");
o v.add("Amit");
o v.add("Ashish");
o v.add("Garima");
o Iterator<String> itr=v.iterator();
o while(itr.hasNext()){
o System.out.println(itr.next());
o }
o }
o }
Output:

Ayush
Amit
Ashish
Garima

EXAMPLE 2:

1. import java.util.*;
2. public class VectorExample1 {
3. public static void main(String args[]) {
4. //Create an empty vector with initial capacity 4
5. Vector<String> vec = new Vector<String>(4);
6. //Adding elements to a vector
7. vec.add("Tiger");
8. vec.add("Lion");
9. vec.add("Dog");
10. vec.add("Elephant");
11. //Check size and capacity
12. System.out.println("Size is: "+vec.size());
13. System.out.println("Default capacity is: "+vec.capacity());
14. //Display Vector elements
15. System.out.println("Vector element is: "+vec);
16. vec.addElement("Rat");
17. vec.addElement("Cat");
18. vec.addElement("Deer");
19. //Again check size and capacity after two insertions
20. System.out.println("Size after addition: "+vec.size());
21. System.out.println("Capacity after addition is: "+vec.capacity());
22. //Display Vector elements again
23. System.out.println("Elements are: "+vec);
24. //Checking if Tiger is present or not in this vector
25. if(vec.contains("Tiger"))
26. {
27. System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
28. }
29. else
30. {
31. System.out.println("Tiger is not present in the list.");
32. }
33. //Get the first element
34. System.out.println("The first animal of the vector is = "+vec.firstElement());
35. //Get the last element
36. System.out.println("The last animal of the vector is = "+vec.lastElement());
37. }
38. }
Test it Now

Output:

Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer

Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e.,
Stack. The stack contains all of the methods of Vector class and also provides its methods
like boolean push(), boolean peek(), boolean push(object o), which defines its properties.

Consider the following example.

Filename: TestJavaCollection4.java
1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:

Ayush
Garvit
Amit
Ashish

Java Hashtable Class

Hashtable in Java is a data structure in which each key is unique and is used to store key-
value pairs. It belongs to Java.util package, which implements Map interface in order to work
with the elements it includes. An important characteristic of a Hashtable is its capability of
providing rapid lookup and insertion operations.

Hash Table uses a hash function to determine an index into an array of buckets or slots,
where each bucket identifies a potential location where a key-value pair can be stored. When
we add an entry to the Hashtable, the hash code of the key is calculated, and the particular
bucket in which the entry will be stored is retrieved based on the hash code.

Hashtable is just like HashMap, but it is synchronized which, so it is thread-safe. This entails
that several threads can operate a Hashtable concurrently without causing data corruption

Points to Remember

o A Hashtable is an array of a list. Each list is known as a bucket. The position of the
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
Hashtable Class Declaration
1. public class Hashtable<k ,v> extends Dictionary<k ,v> implements Map<k ,v>, Cloneable,
Serializable
Hashtable Class Parameters
Let's see the Parameters for java.util.Hashtable class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

import java.util.Hashtable;

public class GFG

public static void main(String args[])

{ // Create a Hashtable of String

// keys and Integer values

Hashtable<String, Integer> hashtable = new Hashtable<>();

// Adding elements to the Hashtable

hashtable.put("One", 1);

hashtable.put("Two", 2);

hashtable.put("Three", 3);

// Displaying the Hashtable elements

System.out.println("Hashtable Elements: " + hashtable);

}
}Test it Now

Output
Hashtable Elements: {One=1, Three=3, Two=2}
Java Hashtable Example: remove()
Hashtable2.java

1. import java.util.*;
2. public class Hashtable2 {
3. public static void main(String args[]) {
4. Hashtable<integer ,string> map=new Hashtable<integer ,string>();
5. map.put(100,"Amit");
6. map.put(102,"Ravi");
7. map.put(101,"Vijay");
8. map.put(103,"Rahul");
9. System.out.println("Before remove: "+ map);
10. // Remove value for key 102
11. map.remove(102);
12. System.out.println("After remove: "+ map);
13. }
14. }

Output:

Before remove: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}


After remove: {103=Rahul, 101=Vijay, 100=Amit}

Enumeration Interface In Java


java.util.Enumeration interface is one of the predefined interfaces, whose object is used
for retrieving the data from collections framework
variable( like Stack, Vector, HashTable etc.) in a forward direction only and not in the
backward direction.

Important Features
 Enumeration is Synchronized.
 It does not support adding, removing, or replacing elements.
 Elements of legacy Collections can be accessed in a forward direction using
Enumeration.
 Legacy classes have methods to work with enumeration and returns Enumeration
objects.

Declaration
public interface Enumeration<E>

Creating Enumeration Object


Vector v = new Vector();
Enumeration e = v.elements();
// Java program to test Enumeration
import java.util.Vector;
import java.util.Enumeration;

public class EnumerationClass {

public static void main(String args[])


{
Enumeration months;
Vector<String> monthNames = new Vector<>();

monthNames.add("January");
monthNames.add("February");
monthNames.add("March");
monthNames.add("April");
monthNames.add("May");
monthNames.add("June");
monthNames.add("July");
monthNames.add("August");
monthNames.add("September");
monthNames.add("October");
monthNames.add("November");
monthNames.add("December");
months = monthNames.elements();

while (months.hasMoreElements()) {
System.out.println(months.nextElement());
}
}
}
Output
January
February
March
April
May
June
July
August
September
October
November
December

Iterator in Java

In Java, an Iterator is one of the Java cursors. Java Iterator is an interface that is practiced
in order to iterate over a collection of Java object components entirety one by one.

Java Iterator Methods


The following figure perfectly displays the class diagram of the Java Iterator interface. It
contains a total of four methods that are:

o hasNext()
o next()
o remove()
o forEachRemaining()

1. import java.io.*;
2. import java.util.*;
3.
4. public class JavaIteratorExample {
5. public static void main(String[] args)
6. {
7. ArrayList<String> cityNames = new ArrayList<String>();
8.
9. cityNames.add("Delhi");
10. cityNames.add("Mumbai");
11. cityNames.add("Kolkata");
12. cityNames.add("Chandigarh");
13. cityNames.add("Noida");
14.
15. // Iterator to iterate the cityNames
16. Iterator iterator = cityNames.iterator();
17.
18. System.out.println("CityNames elements : ");
19.
20. while (iterator.hasNext())
21. System.out.print(iterator.next() + " ");
22.
23. System.out.println();
24. }
25. }
Output:
CityNames elements:
Delhi Mumbai Kolkata Chandigarh Noida

StringTokenizer Class in Java


StringTokenizer class in Java is used to break a string into tokens. A StringTokenizer object
internally maintains a current position within the string to be tokenized.
Java String Tokenization
The StringTokenizer class allows an application to break a string into tokens based on
delimiters.

EXAMPLE:

1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
Output:

my
name
is
khan

Java.util.Random class in Java

Random class is used to generate pseudo-random numbers in java.


Constructors:
 Random(): Creates a new random number generator
 Random(long seed): Creates a new random number generator using a single long seed
import java.util.Random;

public class Test

public static void main(String[] args)

Random random = new Random();

System.out.println(random.nextInt(10));

System.out.println(random.nextBoolean());

System.out.println(random.nextDouble());

System.out.println(random.nextFloat());

System.out.println(random.nextGaussian());

byte[] bytes = new byte[10];

random.nextBytes(bytes);

System.out.printf("[");

for(int i = 0; i< bytes.length; i++)

System.out.printf("%d ", bytes[i]);

System.out.printf("]\n");
System.out.println(random.nextLong());

System.out.println(random.nextInt());

long seed = 95;

random.setSeed(seed);

// Note: Running any of the code lines below

// will keep the program running as each of the

// methods below produce an unlimited random

// values of the corresponding type

/* System.out.println("Sum of all the elements in the IntStream returned = " +

random.ints().count());

System.out.println("Count of all the elements in the DoubleStream returned = " +

random.doubles().count());

System.out.println("Count of all the elements in the LongStream returned = " +

random.longs().count());

*/
}

Output:
4
true
0.19674934340402916
0.7372021
1.4877581394085997
[-44 75 68 89 81 -72 -1 -66 -64 117 ]
158739962004803677
-1344764816

Scanner Class in Java


In Java, Scanner is a class in java.util package used for obtaining the input of the primitive
types like int, double, etc. and strings.
Using the Scanner class in Java is the easiest way to read input in a Java program, though not
very efficient

Input types:
Method Description

nextBoolean() Used for reading Boolean value

nextByte() Used for reading Byte value

nextDouble() Used for reading Double value

nextFloat() Used for reading Float value

nextInt() Used for reading Int value

nextLine() Used for reading Line value


Method Description

nextLong() Used for reading Long value

nextShort() Used for reading Short value

import java.util.Scanner;

// Driver Class

public class ScannerDemo1 {

// main function

public static void main(String[] args)

// Declare the object and initialize with

// predefined standard input object

Scanner sc = new Scanner(System.in);

// String input

String name = sc.nextLine();

// Character input

char gender = sc.next().charAt(0);

// Numerical data input

// byte, short and float can be read

// using similar-named functions.

int age = sc.nextInt();

long mobileNo = sc.nextLong();

double cgpa = sc.nextDouble();


// Print the values to check if the input was

// correctly obtained.

System.out.println("Name: " + name);

System.out.println("Gender: " + gender);

System.out.println("Age: " + age);

System.out.println("Mobile Number: " + mobileNo);

System.out.println("CGPA: " + cgpa);

Input
Geek
F
40
9876543210
9.9
Output
Name: Geek
Gender: F
Age: 40
Mobile Number: 9876543210
CGPA: 9.9

Calendar Class in Java with examples


Calendar class in Java is an abstract class that provides methods for converting date between
a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It
inherits Object class and implements the Comparable, Serializable, Cloneable interfaces.
As it is an Abstract class, so we cannot use a constructor to create an instance. Instead, we
will have to use the static method Calendar.getInstance() to instantiate and implement a
sub-class.
 Calendar.getInstance(): return a Calendar instance based on the current time in the
default time zone with the default locale.
 Calendar.getInstance(TimeZone zone)
 Calendar.getInstance(Locale aLocale)
 Calendar.getInstance(TimeZone zone, Locale aLocale)
Java program to demonstrate getInstance() method:
// Date getTime(): It is used to return a

// Date object representing this

// Calendar's time value.

import java.util.*;

public class Calendar1 {

public static void main(String args[])

Calendar c = Calendar.getInstance();

System.out.println("The Current Date is:" + c.getTime());

Output:
The Current Date is:Tue Aug 28 11:10:40 UTC 2018

import java.util.*;

public class Calendar2 {

public static void main(String[] args)

// creating Calendar object

Calendar calendar = Calendar.getInstance();


// Demonstrate Calendar's get()method

System.out.println("Current Calendar's Year: " + calendar.get(Calendar.YEAR));

System.out.println("Current Calendar's Day: " + calendar.get(Calendar.DATE));

System.out.println("Current MINUTE: " + calendar.get(Calendar.MINUTE));

System.out.println("Current SECOND: " + calendar.get(Calendar.SECOND));

Output:
Current Calendar's Year: 2018
Current Calendar's Day: 28
Current MINUTE: 10
Current SECOND: 45

FILES:

A stream is a sequence of data. I/O Stream refers to a stream that is unlikely a


method to sequentially access a file. I/O Stream means an input source or output destination
representing different types of sources e.g. disk files. The java.io package provides classes
for streams.

Character Stream
In Java, characters are stored using Unicode conventions . Character stream automatically
allows us to read/write data character by character. For example, FileReader and FileWriter
are character streams used to read from the source and write to the destination.
import java.io.*;
public class GFG
{
public static void main(String[] args)
throws IOException
{

// Initially assigning null as we have not read


// anything
FileReader sourceStream = null;

// Try block to check for exceptions


try {

// Reading from file


sourceStream = new FileReader("/Users/mayanksolanki/Desktop/demo.rtf");

// Reading sourcefile and writing content to target file character by character .


int temp;
// If there is content inside file than read
while ((temp = sourceStream.read()) != -1)
System.out.println((char)temp);
// Display message for successful execution of program
System.out.print("Program successfully executed");
}

// finally block that executes for sure where we are closing file connections
// to avoid memory leakage
finally {

// Closing stream as no longer in use


if (sourceStream != null)
sourceStream.close();
}
}
}

Output: Writes content to the target file character by character


Program successfully executed

Byte Stream
Byte streams process data byte by byte (8 bits). For example, FileInputStream is used to
read from the source and FileOutputStream to write to the destination.
import java.io.*;

public class GFG {


public static void main(String[] args)throws IOException
{
// Initially assigning null to objects for reading and writing to file
FileInputStream sourceStream = null;
FileOutputStream targetStream = null;
// Try block to check for exceptions
try {
// Passing the files via local directory
sourceStream = new FileInputStream("/Users/mayanksolanki/Desktop/demo.rtf");
targetStream = new FileOutputStream("/Users/mayanksolanki/Desktop/democopy.rtf");
// Reading source file and writing content to target file byte by byte
int temp;
// If there is content inside file than read
while ((temp = sourceStream.read())!= -1)
targetStream.write((byte)temp);
// Display message for successful execution of program
System.out.print("Program successfully executed");
}
// finally block that executes for sure where we are closing file connections
// to avoid memory leakage
finally {
if (sourceStream != null)
sourceStream.close();
if (targetStream != null)
targetStream.close();
}
}
}

Output:
Program successfully executed
Java IO : Input-output in Java with Examples
Java brings various Streams with its I/O package that helps the user to
perform all the input-output operations. These streams support all the types of
objects, data-types, characters, files etc to fully execute the I/O operations.

Before exploring various input and output streams lets look at 3 standard or
default streams that Java has to provide which are also most common in use:

System.in:
This is the standard input stream(System.in) that is used to read characters from the
keyboard or any other standard input device.
System.out
This is the standard output stream(System.out) that is used to produce the result of a
program on an output device like the computer screen. Here is a list of the various print
functions that we use to output statements:
– print(): This method in Java is used to display a text on the console. This text is passed as
the parameter to this method in the form of String. This method prints the text on the console
and the cursor remains at the end of the text at the console. The next printing takes place from
just here. Syntax:
System.out.print(parameter);
Java I/O Classes
1. Java provides a rich set of classes for performing I/O operations. Some of the key classes include:
2. InputStream and OutputStream: These abstract classes form the foundation for byte-oriented
I/O operations. They provide methods for reading and writing bytes from/to various sources and
destinations.
3. Reader and Writer: These abstract classes are used for character-based I/O operations. They
provide methods for reading and writing characters from/to character-based streams.
4. FileInputStream and FileOutputStream: These classes allow reading from and writing to files
in a byte-oriented manner.
5. FileReader and FileWriter: These classes enable reading from and writing to files using
character-oriented operations.
6. BufferedInputStream and BufferedOutputStream: These classes provide buffering
capabilities, which can significantly improve I/O performance by reducing the number of system
calls.
7. BufferedReader and BufferedWriter: These classes offer buffered reading and writing of
character data, enhancing I/O efficiency when working with character-based streams.
Java - RandomAccessFile
This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving the
cursor we do the read write operations. If end-of-file is reached before the desired number of byte
has been read than EOFException is thrown. It is a type of IOException.

Method
Modi Method Method
fier
and
Type

Void close() It closes this random access file stream and releases any system resources associated with the stream.

FileChan
getChannel() It returns the unique FileChannel object associated with this file.
nel

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.

It converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that
Void writeDouble(double v)
long value to the file as an eight-byte quantity, high byte first.

It converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int
Void writeFloat(float v)
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.

Example
1. import java.io.IOException;
2. import java.io.RandomAccessFile;
3.
4. public class RandomAccessFileExample {
5. static final String FILEPATH ="myFile.TXT";
6. public static void main(String[] args) {
7. try {
8. System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
9. writeToFile(FILEPATH, "I love my country and my people", 31);
10. } catch (IOException e) {
11. e.printStackTrace();
12. }
13. }
14. private static byte[] readFromFile(String filePath, int position, int size)
15. throws IOException {
16. RandomAccessFile file = new RandomAccessFile(filePath, "r");
17. file.seek(position);
18. byte[] bytes = new byte[size];
19. file.read(bytes);
20. file.close();
21. return bytes;
22. }
23. private static void writeToFile(String filePath, String data, int position)
24. throws IOException {
25. RandomAccessFile file = new RandomAccessFile(filePath, "rw");
26. file.seek(position);
27. file.write(data.getBytes());
28. file.close();
29. }
30. }
The myFile.TXT contains text "This class is used for reading and writing to random access file."

after running the program it will contains

This class is used for reading I love my country and my peoplele.

Java.io.File Class in Java

Java File class is Java’s representation of a file or directory pathname.


 t is an abstract representation of files 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, a
String, or another File object. For example,
File a = new File("/usr/local/bin/geeks");
This defines an abstract file name for the geeks file in the directory /usr/local/bin.
This is an absolute abstract file name.

Constructors of Java File Class

 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 of File Class in Java
S. Return
No. Method Description Type

Tests whether the application can


1. canExecute() execute the file denoted by this boolean
abstract pathname.

Tests whether the application can


2. canRead() read the file denoted by this boolean
abstract pathname.

Tests whether the application can


3. canWrite() modify the file denoted by this boolean
abstract pathname.

Compares two abstract pathnames


4. compareTo(File pathname) int
lexicographically.

Atomically creates a new, empty


5. createNewFile() file named by this abstract boolean
pathname.

createTempFile(String Creates an empty file in the


6. File
prefix, String suffix) default temporary-file directory.

7. delete() Deletes the file or directory boolean


denoted by this abstract
S. Return
No. Method Description Type

pathname.

Tests this abstract pathname for


8. equals(Object obj) boolean
equality with the given object.

Tests whether the file or directory


9. exists() denoted by this abstract pathname boolean
exists.

Returns the absolute pathname


10. getAbsolutePath() String
string of this abstract pathname.

Returns an array of strings


11. list() naming the files and directories in String[]
the directory.

Returns the number of


12. getFreeSpace() long
unallocated bytes in the partition.

Returns the name of the file or


13. getName() directory denoted by this abstract String
pathname.

Returns the pathname string of


14. getParent() String
this abstract pathname’s parent.

Returns the abstract pathname of


15. getParentFile() File
this abstract pathname’s parent.
S. Return
No. Method Description Type

Converts this abstract pathname


16. getPath() String
into a pathname string.

Marks the file or directory named


17. setReadOnly() so that only read operations are boolean
allowed.

Tests whether the file denoted by


18. isDirectory() boolean
this pathname is a directory.

Tests whether the file denoted by


19. isFile() this abstract pathname is a normal boolean
file.

Tests whether the file named by


20. isHidden() this abstract pathname is a hidden boolean
file.

Returns the length of the file


21. length() denoted by this abstract long
pathname.

Returns an array of abstract


22. listFiles() pathnames denoting the files in File[]
the directory.

Creates the directory named by


23. mkdir() boolean
this abstract pathname.

24. renameTo(File dest) Renames the file denoted by this boolean


S. Return
No. Method Description Type

abstract pathname.

setExecutable(boolean A convenience method to set the


25. boolean
executable) owner’s execute permission.

setReadable(boolean A convenience method to set the


26. boolean
readable) owner’s read permission.

setReadable(boolean
Sets the owner’s or everybody’s
27. readable, boolean boolean
read permission.
ownerOnly)

setWritable(boolean A convenience method to set the


28. boolean
writable) owner’s write permission.

Returns the pathname string of


29. toString() String
this abstract pathname.

Constructs a file URI that


30. toURI() URI
represents this abstract pathname.

Java File Class Examples

Example 1: Program to check if a file or directory physically exists or not.


 Java

import java.io.File;
// Displaying file property
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


System.out.println("File name :" + f.getName());
System.out.println("Path: " + f.getPath());
System.out.println("Absolute path:" + f.getAbsolutePath());
System.out.println("Parent:" + f.getParent());
System.out.println("Exists :" + f.exists());
if (f.exists())
{
System.out.println("Is writable:" + f.canWrite());
System.out.println("Is readable" + f.canRead());
System.out.println("Is a directory:" + f.isDirectory());
System.out.println("File Size in bytes "+ f.length());
}
}
}

Output
File name :file.txt
Path: file.txt
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
Parent:null
Exists :true
Is writable:true
Is readabletrue
Is a directory:false
File Size in bytes 20

You might also like