0% found this document useful (0 votes)
5 views11 pages

Q.1 What Is File? Explain Functions of File With Explanation and Example. Java - Io Package File Class

Uploaded by

Agrita Anand
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)
5 views11 pages

Q.1 What Is File? Explain Functions of File With Explanation and Example. Java - Io Package File Class

Uploaded by

Agrita Anand
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
You are on page 1/ 11

CTBTCSE SIII P4 – Java Programming Unit-4 (I/O Related Classes and Multi-threading)

Q.1 What is File? Explain functions of File • public long length()


with explanation and example. Returns the length of the file denoted by this
pathname.
java.io package • public boolean delete()
File Class It returns true and delete the specified file or
• Java File class represents the files and directory folder if it is found.
pathnames in an abstract manner. • public void deleteOnExit()
• This class is used for creation of files and Requests that the file or directory denoted by
directories, file searching, file deletion etc. this abstract pathname be deleted when the
• The File object represents the actual virtual machine terminates.
file/directory on the disk. • public String[] list()
• There are following constructors to create a File Returns an array of strings naming the files
object: and directories in the directory denoted by
this abstract pathname.
• File(String pathname) • public String[] list(FilenameFilter)
• File(File parent, String child); Returns an array of strings naming the files
• File(String parent, String child) and directories in the directory denoted by
this abstract pathname that satisfy the
SN Methods with Description specified filter.
• public String getName() • public File[] listFiles()
Returns the name of the file or directory Returns an array of abstract pathnames
denoted by this abstract pathname. denoting the files in the directory denoted by
public String getParent() this abstract pathname.

Returns the pathname string of this abstract • public File[] listFiles(FileFilter)
pathname's parent. Returns an array of abstract pathnames
• public String getPath() denoting the files and directories in the
Converts this abstract pathname into a directory denoted by this abstract pathname
pathname string. that satisfy the specified filter.
• public String getAbsolutePath() • public boolean mkdir()
Returns the absolute pathname string of this It returns true and create the directory if
abstract pathname. parent directory is found. It creates always
only one directory.
• public boolean canRead()
Returns true if and only if the file specified by • public boolean mkdirs()
this abstract pathname exists and can be read Returns true if and only if the directory was
by the application; false otherwise. created, along with all necessary parent
directories; false otherwise.
• public boolean canWrite()
Returns true if and only if the file system is • public boolean renameTo(File dest)
allowed to write to the file; false otherwise. Returns true if and only if the renaming
succeeded; false otherwise.
• public boolean isDirectory()
Returns true if and only if the file denoted by • public boolean setLastModified(long time)
pathname exists and is a directory; false Sets the last-modified time of the file or
otherwise. directory named by this abstract pathname.
• public boolean isFile() • public static File createTempFile(String
Returns true if and only if the file denoted by prefix, String suffix, File directory) throws
pathname exists and is a normal file; false IOException
otherwise. Creates a new empty file in the specified
directory, using the given prefix and suffix
• public long lastModified()
strings to generate its name.
Returns a long value representing the time the
file was last modified, measured in ________________________________________________________
milliseconds since the epoch (00:00:00 GMT, ________________________________________________________
January 1, 1970), or 0L if the file does not exist ________________________________________________________
or if an I/O error occurs. ________________________________________________________

School of Cyber Security and Digital Forensics, NFSU, Gandhinagar Page 1


Prepared by: Dr. Parag C. Shukla (Assistant Professor) Email: [email protected]
CTBTCSE SIII P4 – Java Programming Unit-4 (I/O Related Classes and Multi-threading)

Example (Basic file operations) ________________________________________________________


import java.io.File; ________________________________________________________
import java.util.Date; ________________________________________________________
class FileOprations ________________________________________________________
{
________________________________________________________
public static void main(String []args){
________________________________________________________
File f = new File(args[0]); ________________________________________________________
System.out.println(f.isFile()); ________________________________________________________
System.out.println(f.isDirectory()); ________________________________________________________
System.out.println(f.isHidden()); ________________________________________________________
System.out.println(f.canRead()); ________________________________________________________
System.out.println(f.canWrite()); ________________________________________________________
System.out.println(f.canExecute()); ________________________________________________________
System.out.println(f.isAbsolute()); ________________________________________________________
System.out.println(f.getName()); ________________________________________________________
System.out.println(f.getPath());
________________________________________________________
System.out.println(f.getAbsolutePath());
________________________________________________________
System.out.println(Math.ceil((float)f.length()/1024)
+" KB"); ________________________________________________________
System.out.println(new Date(f.lastModified())); ________________________________________________________
}
}
Example (Operating System operations)
import java.io.File;
import java.util.Date;
class TestDemo
{
public static void main(String []args)
{
File f1 = new File(args[0]);
File f2 = new File(args[1]);
System.out.println(f1.renameTo(f2));
//System.out.println(f1.mkdir());
//System.out.println(f1.mkdirs());
//System.out.println(f1.delete());
}
}
Example (Listing file from specified directory)
import java.io.*;
import java.util.Date;
________________________________________________________
class TestDemo
________________________________________________________
{
public static void main(String []args){ ________________________________________________________
File f = new File(args[0]); ________________________________________________________
if(f.isDirectory()) ________________________________________________________
{ ________________________________________________________
String name[] = f.list(); ________________________________________________________
for(String n : name) ________________________________________________________
System.out.println(n); ________________________________________________________
} ________________________________________________________
} ________________________________________________________
}

School of Cyber Security and Digital Forensics, NFSU, Gandhinagar Page 2


Prepared by: Dr. Parag C. Shukla (Assistant Professor) Email: [email protected]
CTBTCSE SIII P4 – Java Programming Unit-4 (I/O Related Classes and Multi-threading)

Q.2 Explain File Filter and FilenameFilter FileFilter


with Example. • The FileFilter interface in java can be used to
filter the files from a given directory.
FilenameFilter • Instances of this interface may be passed to
• FilenameFilter is an interface in Java that is used the listFiles(FileFilter) method of the File.
to filter file names, such as those returned from a • It has abstract methods
call to a File object's listFiles() or list() method. public boolean accept(File pathname)
• If listFiles() is called with no parameters, it
returns all File objects in a directory. import java.io.*;
• If we pass in a filter as a parameter, we can
import java.util.Date;
selectively return a subset of those objects.
class TestDemo
• Creating an object that implements
FilenameFilter requires us to implement the {
public boolean accept(File dir, String name) public static void main(String []args) {
method. File f = new File(args[0]);
• The dir object is the parent directory of the file,
and name is the name of the file. if(f.isDirectory())
• If accept() returns true, the file will be returned {
in the array of File objects from the call to File name[] = f.listFiles(new FileFilter()
listFiles(). {
• If accept() returns false, the file isn't returned by public boolean accept(File f1)
the call to listFiles(). {
return f1.length()>2048;
Example (Listing java files) }
import java.io.*; });
import java.util.Date;
class TestDemo for(File n : name)
{ System.out.println(n.getName()+"
public static void main(String []args){ "+n.length());
File f = new File(args[0]); } // end of if
} // end of main
if(f.isDirectory()) {
}
File name[] = f.listFiles(new FilenameFilter() ________________________________________________________
{ Example (Listing Images)
public boolean accept(File path,String name) import java.io.*;
{ class ImageListing implements FileFilter
File f1 = new File(path,name); {
//return f1.isHidden(); private final String[] okFileExtensions =
return name.endsWith(".java"); new String[] {"jpg", "png", "gif"};
}
}); public boolean accept(File file)
{
for(File n : name) for (String extension : okFileExtensions)
System.out.println(n.getName()+" "+n.length()); {
if(file.getName().endsWith(extension))
} // end of if return true;
}
} // end of main return false;
}//end of class }
________________________________________________________ }
________________________________________________________

School of Cyber Security and Digital Forensics, NFSU, Gandhinagar Page 3


Prepared by: Dr. Parag C. Shukla (Assistant Professor) Email: [email protected]
CTBTCSE SIII P4 – Java Programming Unit-4 (I/O Related Classes and Multi-threading)

Q.3 STREAM CLASSES Constructors of RandomAccessFile


• Java encapsulates Stream under java.io 1. RandomAccessFile(String file, String mode)
package. 2. RandomAccessFile(File file, String mode)
• Java defines two types of streams. They are,
1. Byte Stream : It provides a convenient • Constructor takes name of the file as a
means for handling input and output of byte. parameter and mode as a parameter.
2. Character Stream : It provides a convenient • mode could be "r", "rw" or "rwd"
means for handling input and output of
characters. Character stream uses Unicode Methods of RandomAccessFile
and therefore can be internationalized. public void seek(long position)
public long getFilePointer()
Byte Stream public long length()
1) InputStream : It is used to read data in byte
stream. • RandomAccessFile maintains a file pointer.
2) OutputStream : It is used to write data in byte • The file pointer indicates the position within
stream. the file where the next read or write
operation will be done.
Character Stream • Initially file pointer is at 0 position.
1) Reader : It is used to read data in char stream. • The getFilePointer() method returns the
2) Writer : It is used to write data in char stream. current value of the file pointer.
• Current value of file pointer can be changed
• OutputStream and Writer classes have write by using the seek() method.
methods to write the data to some • length() method returns size of the file in
destination. bytes.
• InputStream and Reader similarly have read
methods to read data from the source. Example (RandomAccessFile)
• All the stream classes implements Closeable
interface, which has only one method called import java.io.*;
close(). class TestDemo {
• It is used to release any system resources public static void main(String []args)
which are used by the stream. throws Exception {

RandomAccessFile r =
Q.4 Explain RandomAccessFile with new RandomAccessFile(args[0],"r");
Example.
String str;
• A FileInputStream can be used to read from a r.seek(10);
file, and a FileOutputStream can be used to System.out.println(r.length());
write to a file.
• We may be interested in reading and writing System.out.println(r.getFilePointer());
to the same file. while((str=r.readLine())!=null)
• For this, we have a class called System.out.println(str);
RandomAccessFile which can be used for
reading and writing to the file. System.out.println(r.getFilePointer());
• RandomAccessFile implements Closable, }
DataInput and DataOutput interface. }

School of Cyber Security and Digital Forensics, NFSU, Gandhinagar Page 4


Prepared by: Dr. Parag C. Shukla (Assistant Professor) Email: [email protected]
CTBTCSE SIII P4 – Java Programming Unit-4 (I/O Related Classes and Multi-threading)

Q.5 Explain ObjectOutputStream and transient


ObjectInputStream OR Explain Serialization • The keyword transient in Java used to
in detail. indicate that the variable should not be
serialized.
• ObjectOutputStream is directly sub classed • By default all the variables in the object is
from the OutputStream class. converted to persistent state.
• It implements ObjectOutput interface. • In some cases, you may want to avoid
• Constructor of ObjectOutputStream requires persisting some variables because you don’t
an OutputStream as a parameter. have the necessity to transfer across the
network.
ObjectOutput interface • So, you can declare those variables as
• It extends the DataOutput interface. transient.
• It inherits all the methods of DataOutput • If the variable is declared as transient, then it
interface and has one additional method will not be persisted. It is the main purpose
called writeObject(). of the transient keyword.
• For example in Account class has an instance
• ObjectOutputStream class has the variable for PIN number. This is secure
capabilities of handling all the primitive data information and we would not like this to be
types similar to the DataOutputStream. persisted using the writeObject() method.
• Additionally it can also handle Objects. This can be done by declaring such fields to
• The writeObject() method gives the be transient.
capability of persisting objects.
ObjectInputStream
Serialization • It is directly sub-classed from InputStream
• Serialization is the process of converting an class.
object into a sequence of bytes such that • It implements ObjectInput interface.
those bytes can be used to recreate the object • Constructor of ObjectInputStream requires
in same state. InputStream as a parameter.
• Serialization is the process of making the
object’s state is persistent. ObjectInput interface
• That means the state of the object is • This interface extends the DataInput
converted into stream of bytes and stored in interface.
a file. • ObjectInput interface inherits all the
• In the same way we can use the de- methods from the DataInput interface and
serilization concept to bring back the object’s has one additional method called
state from bytes. readObject().
• This is one of the important concept in Java • ObjectInputStream class has the capabilities
programming because this serialization is of handling all the primitive data types
mostly used in the network programming. similar to the DataInputStream.
• Only instance of classes implementing the • Additionally it can also handle Objects.
Serializable interface may be serialized using • readObject() method is used for deserializing
writeObject() method. an object.
• Serializable is a marker interface without any
methods. Example on next page
________________________________________________________
________________________________________________________
________________________________________________________
_______________________________________________________

School of Cyber Security and Digital Forensics, NFSU, Gandhinagar Page 5


Prepared by: Dr. Parag C. Shukla (Assistant Professor) Email: [email protected]
CTBTCSE SIII P4 – Java Programming Unit-4 (I/O Related Classes and Multi-threading)

Example • In the above example, the variable empid is


class Employee implements Serializable declared as transient, so it will not be stored
{ in the persistent storage.
private transient int empid; ________________________________________________________
private String name; ________________________________________________________
private int salary; ________________________________________________________
Employee(){} ________________________________________________________
Employee(int empid,String name,int salary){ ________________________________________________________
this.empid=empid; ________________________________________________________
this.name=name; ________________________________________________________
this.salary=salary; ________________________________________________________
} ________________________________________________________
public String toString() ________________________________________________________
{ ________________________________________________________
return empid+" "+name+" "+salary+"\n"; ________________________________________________________
}
}

class TestEmployee
{
public static void main(String []args)
throws Exception
{
Employee e1 = new Employee(101,"Ram",590);
Employee e2 = new Employee(102,"Sita",470);
Employee e3 = new Employee(103,"Lax",450);

//Serialization
ObjectOutputStream oos = new
ObjectOutputStream(new
FileOutputStream(args[0]));

oos.writeObject(e1);
oos.writeObject(e2);
oos.writeObject(e3);
oos.flush(); ________________________________________________________
oos.close(); ________________________________________________________
________________________________________________________
//Deserialization ________________________________________________________
ObjectInputStream ois = new ________________________________________________________
ObjectInputStream(new ________________________________________________________
FileInputStream(args[0])); ________________________________________________________
Employee e4 = (Employee)ois.readObject(); ________________________________________________________
Employee e5 = (Employee)ois.readObject(); ________________________________________________________
Employee e6 = (Employee)ois.readObject(); ________________________________________________________
System.out.println(e4+""+e5+""+e6); ________________________________________________________
} ________________________________________________________
} ________________________________________________________

School of Cyber Security and Digital Forensics, NFSU, Gandhinagar Page 6


Prepared by: Dr. Parag C. Shukla (Assistant Professor) Email: [email protected]
CTBTCSE SIII P4 – Java Programming Unit-4 (I/O Related Classes and Multi-threading)

Q.6 Write a code to copy content from one file Q.8 Write a Java code to display content of
to another file. file with line number and display only even
lines of given file.
import java.io.*; import java.io.*;
import java.util.*;
class CopyFile class FileReadDemo3{
{ public static void main(String[] args) throws
public static void main(String []args) Exception {
throws Exception FileInputStream fis = new
{ FileInputStream(args[0]);
InputStream i = LineNumberReader lr = new
new FileInputStream(args[0]); LineNumberReader(new InputStreamReader
(fis));
byte[] b = new byte[i.available()]; String line;
i.read(b); while((line=lr.readLine())!=null){
FileWriter f = new FileWriter(args[1]); if(lr.getLineNumber()%2==0)
f.write(new String(b)); System.out.println(lr.getLineNumber()+" :”
f.close(); +line);
} }
} fis.close();
}
Q.7 Write a code to read content from file. }

import java.io.*; ________________________________________________________


class TestDemo ________________________________________________________
{ ________________________________________________________
public static void main(String []args) ________________________________________________________
throws Exception ________________________________________________________
{ ________________________________________________________
File f = new File(args[0]); ________________________________________________________
if(f.exists()) ________________________________________________________
{ ________________________________________________________
FileInputStream in = ________________________________________________________
new FileInputStream(f); ________________________________________________________
int ch; ________________________________________________________
while((ch=in.read())!=-1) ________________________________________________________
System.out.print((char)ch); ________________________________________________________
} ________________________________________________________
} ________________________________________________________
} ________________________________________________________
________________________________________________________
________________________________________________________ ________________________________________________________
________________________________________________________ ________________________________________________________
________________________________________________________ ________________________________________________________
________________________________________________________ ________________________________________________________
________________________________________________________ ________________________________________________________
________________________________________________________ ________________________________________________________
________________________________________________________ ________________________________________________________

School of Cyber Security and Digital Forensics, NFSU, Gandhinagar Page 7


Prepared by: Dr. Parag C. Shukla (Assistant Professor) Email: [email protected]
CTBTCSE SIII P4 – Java Programming Unit-4 (I/O Related Classes and Multi-threading)

Q.9 Explain Thread Life Cycle with Example after calling resume or after completion of sleep
Program. OR Explain Thread States. thread will be again in Runnable State.

class Test extends Thread DEAD State: After completion of run() method,
{ Thread will be in Dead State.
Test()
{ ________________________________________________________
super(); // NEW or BORN ________________________________________________________
start(); ________________________________________________________
} ________________________________________________________
//Runnable State ________________________________________________________
public void run() ________________________________________________________
{ ________________________________________________________
try{ ________________________________________________________
Thread.sleep(5000); // BLOCKED ________________________________________________________
}catch(InterruptedException e){} ________________________________________________________
} ________________________________________________________
//DEAD ________________________________________________________
} ________________________________________________________
________________________________________________________
________________________________________________________
________________________________________________________

NEW State: Initially, when a new instance of


Thread is created, it is in NEW or BORN state.

RUNNABLE State : When we call start() method


________________________________________________________
on the instance of Thread, the state changed to
________________________________________________________
RUNNABLE. Initially Runnable State represents
________________________________________________________
the state when thread is either ready for
________________________________________________________
execution.
________________________________________________________
________________________________________________________
________________________________________________________
BLOCKED State: When we call sleep, supend or
________________________________________________________
wait method thread will be in BLOCKED state,

School of Cyber Security and Digital Forensics, NFSU, Gandhinagar Page 8


Prepared by: Dr. Parag C. Shukla (Assistant Professor) Email: [email protected]
CTBTCSE SIII P4 – Java Programming Unit-4 (I/O Related Classes and Multi-threading)

Q.10. Explain ways to create a Thread.


class TestDemo
There are two ways to create a Thread {
1. extends Thread public static void main(String []args)
2. implements Runnable {
3. Anonymously Test t = new Test();
Thread t1 = new Thread(t);
1) extends Thread t1.start();
import java.util.Date; }
class Test extends Thread }
{
Test(){ 3) Creating Thread Anonymously
super("Clock Thread");
start(); import java.util.Date;
} class TestDemo
public void run() {
{ public static void main(String []args)
while(true){ {
System.out.println(new Date()); Thread t = new Thread()
try{ {
Thread.sleep(1000); public void run()
}catch(Exception e){} {
} while(true){
} System.out.println(new Date());
} try{
class TestDemo Thread.sleep(1000);
{ }catch(Exception e){}
public static void main(String []args) } // End of while
{ }
Test t = new Test(); };
} t.start();
} }
}

2) Runnable Example ________________________________________________________


import java.util.Date; ________________________________________________________
class Test implements Runnable ________________________________________________________
{ ________________________________________________________
Test(){} ________________________________________________________
public void run() ________________________________________________________
{ ________________________________________________________
while(true){ ________________________________________________________
System.out.println(new Date()); ________________________________________________________
try{ ________________________________________________________
Thread.sleep(1000); ________________________________________________________
}catch(Exception e){} ________________________________________________________
} ________________________________________________________
} ________________________________________________________
} ________________________________________________________

School of Cyber Security and Digital Forensics, NFSU, Gandhinagar Page 9


Prepared by: Dr. Parag C. Shukla (Assistant Professor) Email: [email protected]
CTBTCSE SIII P4 – Java Programming Unit-4 (I/O Related Classes and Multi-threading)

Q.11. Explain Synchronization with Example. public void run()


{
• There are two types of thread Table.printTable(5);
synchronization }
o mutual exclusive and }
o inter-thread communication. class Test1 extends Thread
{
• Mutual Exclusive helps keep threads from Test1()
interfering with one another while {
sharing data. This can be done by three super("My Thread2");
ways in java: start();
o by synchronized method }
o by synchronized block public void run()
o by static synchronization {
Table.printTable(15);
• Synchronization is built around an }
internal entity known as the lock or }
monitor. class TestDemo
• Every object has an lock associated with {
it. public static void main(String args[])
• By convention, a thread that needs {
consistent access to an object's fields has Test t = new Test();
to acquire the object's lock before Test1 t1 = new Test1();
accessing them, and then release the lock }
when it's done with them. }
________________________________________________________
Example ________________________________________________________
________________________________________________________
import java.util.*; ________________________________________________________
class Table{ ________________________________________________________
synchronized public static void printTable(int n) ________________________________________________________
{ ________________________________________________________
for(int i=1;i<=5;i++) ________________________________________________________
{ ________________________________________________________
System.out.print(i*n+" "); ________________________________________________________
try{ ________________________________________________________
Thread.sleep(1000); ________________________________________________________
}catch(InterruptedException e){} ________________________________________________________
} ________________________________________________________
System.out.println(); ________________________________________________________
} ________________________________________________________
} ________________________________________________________
class Test extends Thread ________________________________________________________
{ ________________________________________________________
Test() ________________________________________________________
{ ________________________________________________________
super("MyThread1"); ________________________________________________________
start(); ________________________________________________________
}

School of Cyber Security and Digital Forensics, NFSU, Gandhinagar Page 10


Prepared by: Dr. Parag C. Shukla (Assistant Professor) Email: [email protected]
CTBTCSE SIII P4 – Java Programming Unit-4 (I/O Related Classes and Multi-threading)

Q.12 Explain Use of join() method with Q.13. Differentiate Daemon Thread Vs
Example. Non-Daemon Thread

• The join() method waits for a thread to die. Daemon Thread Non-Daemon
In other words, it causes the currently Thread
running threads to stop executing until the These threads are generally These threads are
thread it joins with completes its task. known as a "Service generally known as a
• Syntax Provider" thread. "User thread".
o public void join() throws These threads should not These threads are
InterruptedException be used to execute program created by
o public void join(long milliseconds) code but system code. programmer. It
throws InterruptedException generally meant to
run program code.
class Test extends Thread These thread run in parallel JVM doesn't
{ to your code but JVM can terminates unless all
Test(String name) kill them anytime. When the user thread
{ JVM finds no user threads, terminate.
super(name); it stops and all daemon
start(); thread terminate instantly.
} We can set non-daemon We can set daemon
public void run() thread to daemon using thread to non-
{ setDaemon(true) daemon using
for(int i=1;i<=5;i++){ System.out.println(i+" : setDaemon(false)
"+this);
try{
Thread.sleep(1500); ________________________________________________________
}catch(Exception e){} ________________________________________________________
} ________________________________________________________
} ________________________________________________________
} ________________________________________________________
class TestDemo ________________________________________________________
{ ________________________________________________________
public static void main(String []args) ________________________________________________________
{ ________________________________________________________
Test t1 = new Test("One"); ________________________________________________________
Test t2 = new Test("Two"); ________________________________________________________
Test t3 = new Test("Three"); ________________________________________________________
try{ ________________________________________________________
t1.join(); ________________________________________________________
t2.join(); ________________________________________________________
t3.join(); ________________________________________________________
}catch(Exception e){} ________________________________________________________
System.out.println("Main Exit"); ________________________________________________________
} ________________________________________________________
} ________________________________________________________
________________________________________________________
Main Thread will wait for all child thread to ________________________________________________________
finish. ________________________________________________________
________________________________________________________

School of Cyber Security and Digital Forensics, NFSU, Gandhinagar Page 11


Prepared by: Dr. Parag C. Shukla (Assistant Professor) Email: [email protected]

You might also like