0% found this document useful (0 votes)
2 views49 pages

JAVA PROGRAMS Msword&rendition 1

The document outlines a Java Programming Lab for II B.Tech II semester students, detailing several programming assignments. These include creating a simple calculator using Java Applet, developing applets for displaying messages and computing factorials, performing integer division with exception handling, implementing multi-threading, and managing a doubly linked list. Each program includes code snippets and instructions for implementation, focusing on practical application of Java concepts.

Uploaded by

kvenu8637
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views49 pages

JAVA PROGRAMS Msword&rendition 1

The document outlines a Java Programming Lab for II B.Tech II semester students, detailing several programming assignments. These include creating a simple calculator using Java Applet, developing applets for displaying messages and computing factorials, performing integer division with exception handling, implementing multi-threading, and managing a doubly linked list. Each program includes code snippets and instructions for implementation, focusing on practical application of Java concepts.

Uploaded by

kvenu8637
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 49

Java Programming Lab II B.Tech II sem.

R18

Program 1:
Use Eclipse or Netbean platform and acquaint with the various menus. Create a test project, add a test
class and run it. See how you can use auto suggestions, auto fill. Try code formatter and code refactoring
like renaming variables, methods and classes. Try debug step by step with a small program of about 10
to 15 lines which contains at least one if else condition and a for loop.
About Eclipse IDE

In the context of computing, Eclipse is an integrated development environment (IDE) for developing
applications using the Java programming language and other programming languages such as C/C++,
Python, PERL, Ruby etc. The Eclipse platform which provides the foundation for the Eclipse IDE is
composed of plug-ins and is designed to be extensible using additional plug-ins. Developed using Java,
the Eclipse platform can be used to develop rich client applications, integrated development
environments and other tools. Eclipse can be used as an IDE for any programming language for which a
plug-in is available.

Opening the New Java Class wizard


You can use the New Java Class wizard to create a Java class. The Java Class wizard can be invoked
in different ways:

 By clicking on the File menu and selecting New > Class

 By right clicking in the package explorer and selecting New > Class

 By clicking on the class drop down button ( ) and selecting class ( )

Before bringing up the New Java Class wizard, if possible, select the package in which the class is to be
created so that the wizard can automatically fill in the package name for you.

Using the New Java Class wizard


Once the java class wizard comes up:

 Ensure the source folder and package are correct

 Enter the class name

 Select the appropriate class modifier

 Enter the super class name or click on the Browse button to search for an existing class

 Click on the Add button to select the interfaces implemented by this class

 Examine and modify the check boxes related to method stubs and comments

 Click on the Finish button

1
Java Programming Lab II B.Tech II sem. R18

Program 2:

Write a java program that works as simple calculator . Use a grid layout to arrange
buttons for the digits and for the +,-,*,% operations. add a textfield to display the result.
Handle any possible exceptions like divide by zero

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Cal" width=300 height=300>
</applet>
*/
public class Cal extends Applet
implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);

2
Java Programming Lab II B.Tech II sem. R18

for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
3
Java Programming Lab II B.Tech II sem. R18

}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
char ch=str.charAt(0);
try
{
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
4
Java Programming Lab II B.Tech II sem. R18

t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
5
Java Programming Lab II B.Tech II sem. R18

else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
catch (Exception e)
{
t1.setText(e.toString());
}

}
}

6
Java Programming Lab II B.Tech II sem. R18

OUTPUT:

7
Java Programming Lab II B.Tech II sem. R18

8
Java Programming Lab II B.Tech II sem. R18

Program 3.

a) Develop an applet in Java that displays a simple message

import java.awt.*;
import java.applet.*;
/*
<applet code="MyApplet" height=500 width=500>
</applet>
*/
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
Font font = new Font("Serif", Font.PLAIN, 24);
g.setFont(font);
g.drawString("Welcome to applets",120,120);
}
}

9
Java Programming Lab II B.Tech II sem. R18

OUTPUT:

10
Java Programming Lab II B.Tech II sem. R18

PROGRAM 3
b) Develop an applet in java that receives an integer in one text field, and computes its
factorial value and returns it in another text field, when the button named Compute is
clicked.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener
{
Button b;
TextField tf,tf1;
public void init()
{
tf=new TextField("Eneter a value");
tf1=new TextField("Results will appear here");
tf.setBounds(30,40,150,20);
tf1.setBounds(30,80,150,20);
b=new Button("Compute ");
b.setBounds(80,150,60,50);
add(b);
add(tf);
add(tf1);
b.addActionListener(this);
setLayout(null);
}

11
Java Programming Lab II B.Tech II sem. R18

public void actionPerformed(ActionEvent e)


{
int n,fact=1;
try
{
n=Integer.parseInt(tf.getText());
}
catch(Exception e1)
{
tf.setText(" Invalid Number Try Again");
return 0;
}
for(int i=1;i<=n;i++)
fact=fact*i;
tf1.setText("factorial is "+fact);
}
}

/*
<applet code="EventApplet" height=500 width=500>
</applet>
*/

12
Java Programming Lab II B.Tech II sem. R18

OUTPUT:

13
Java Programming Lab II B.Tech II sem. R18

14
Java Programming Lab II B.Tech II sem. R18

Program 4:

Write a java program that causes a user interface to perform integer divisions. the user
enters two numbers in textfields Num1 and Num2 . the division of num1 and num2 is
displayed in the result field when the divide button is clicked. if Num1 or num2 were not an
integer , the program would through a NumberFormatException . If Num2 were zero , the
program would through an arithmeticException . Display the exception in a message dialog
box.

import javax.swing.JOptionPane;
import javax.swing.*;
import java.awt.*;

public class NumDiv extends JFrame


{
private JButton jButton1;
private JLabel jLabel1;
private JLabel jLabel2;
private JTextField t1;
private JTextField t2;
public NumDiv()
{
initComponents();
}
private void initComponents()
{
t1 = new JTextField();
t2 = new JTextField();
jLabel1 = new JLabel();
jLabel2 = new JLabel();

15
Java Programming Lab II B.Tech II sem. R18

jButton1 = new JButton();


setLayout(new FlowLayout());
setSize(200,200);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
t1.setColumns(10);
t2.setColumns(10);
jLabel1.setText("Enter first Number");
jLabel2.setText("Enter Second Number");
jButton1.setText("Divide");
jButton1.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton1ActionPerformed(evt);
}
}
add(jLabel1);
add(t1);
add(jLabel2);
add(t2);
add(jButton1);
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)


{
try
{
16
Java Programming Lab II B.Tech II sem. R18

int n1=Integer.parseInt( t1.getText());


int n2=Integer.parseInt( t2.getText());
if(n2==0)
throw new ArithmeticException();
double n3=(double) n1/n2;
JOptionPane.showMessageDialog(rootPane, "Division results is: "+n3);
}
catch(NumberFormatException ne)
{
JOptionPane.showMessageDialog(rootPane, ne);
}
catch(ArithmeticException ne)
{
JOptionPane.showMessageDialog(rootPane, ne);
}
}
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new NumDiv().setVisible(true);
}
}
}
}
17
Java Programming Lab II B.Tech II sem. R18

OUTPUT:

18
Java Programming Lab II B.Tech II sem. R18

Program 5:
program on multi threading here we create three threads First thread will generate a
random no, then second thread will print square of that number if it is Even Number,Third
will print cube of given no if it is odd number....
import java.util.*;
class MultiThread
{
int n=0;
boolean n_set=false;
public void n_set()
{
Random r=new Random();
while(n_set==true)
n=r.nextInt(100);
n_set=true;
System.out.println("Random no is "+n);
try
{
Thread.sleep(1000);
}
catch(Exception e){}
}
public void n_sq()
{
if(n_set==true && n%2==0)
{
System.out.println("square of given "+n+" is"+n*n);
n_set=false;
19
Java Programming Lab II B.Tech II sem. R18

}
}

public void n_cube()


{
if(n_set==true && (n%2)!=0)
{
System.out.println("cube of given "+n+" is"+n*n*n);
n_set=false;
}
}
}
class M11
{
public static void main(String a[])
{
final MultiThread l=new MultiThread();
final Thread t1= new Thread();
public void run()
{
while(true)
{
l.n_set();
}
}
}

20
Java Programming Lab II B.Tech II sem. R18

t1.start();
Thread t2 =new Thread();
public void run()
{
while(true)
l.n_sq();
}}
t2.start();
Thread t3 = new Thread();
public void run()
{
while(true)
l.n_cube();
}
}
t3.start();
}
}

21
Java Programming Lab II B.Tech II sem. R18

OUTPUT:

22
Java Programming Lab II B.Tech II sem. R18

Program 6

Write a Java program for the following:

i) Create a doubly linked list of elements.


ii) Delete a given element from the above list.
iii) Display the contents of the list after deletion.

// Java program to create and delete a node from doubly linked list

class LinkedList {

static Node head = null;

class Node
{
int data;
Node next, prev;

Node(int d)
{
data = d;
next = prev = null;
}
}

/*Function to delete a node in a Doubly Linked List.


head_ref --> pointer to head node pointer.
del --> pointer to node to be deleted. */
void deleteNode(Node head_ref, Node del) {

/* base case */
if (head == null || del == null) {
return;
}

/* If node to be deleted is head node */


if (head == del) {
head = del.next;
}

23
Java Programming Lab II B.Tech II sem. R18

/* Change next only if node to be deleted is NOT the last node */


if (del.next != null)
{
del.next.prev = del.prev;
}

/* Change prev only if node to be deleted is NOT the first node */


if (del.prev != null)
{
del.prev.next = del.next;
}

/* Finally, free the memory occupied by del*/


return;
}

/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning of the Doubly Linked List */
void push(Node head_ref, int new_data)
{
/* allocate node */
Node new_node = new Node(new_data);

/* since we are adding at the begining,


prev is always NULL */
new_node.prev = null;

/* link the old list off the new node */


new_node.next = (head);

/* change prev of head node to new node */


if ((head) != null) {
(head).prev = new_node;
}

/* move the head to point to the new node */


(head) = new_node;
}

24
Java Programming Lab II B.Tech II sem. R18

/*Function to print nodes in a given doubly linked list


This function is same as printList() of singly linked lsit */
void printList(Node node)
{
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}

public static void main(String[] args)


{
LinkedList list = new LinkedList();

/* Let us create the doubly linked list 10<->8<->4<->2 */


list.push(head, 2);
list.push(head, 4);
list.push(head, 8);
list.push(head, 10);

System.out.println("Original Linked list ");


list.printList(head);

/* delete nodes from the doubly linked list */


list.deleteNode(head, head); /*delete first node*/

list.deleteNode(head, head.next); /*delete middle node*/

list.deleteNode(head, head.next); /*delete last node*/


System.out.println("");

/* Modified linked list will be NULL<-8->NULL */


System.out.println("Modified Linked List");
list.printList(head);
}
}

25
Java Programming Lab II B.Tech II sem. R18

Output:

Original Linked list


10 8 4 2
Modified Linked List
8

26
Java Programming Lab II B.Tech II sem. R18

Program 7:
Write a java program that simulates a traffic light. the program lets the user select one of
the three lights : red,Yellow,Green with radio buttons. On selecting a button, an
appropriate message with Stop or Ready Or GO should appear above button in selected
color Initially there is no message shown.
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
/*
<applet code="TraficLight" height=500 width=500> </applet>
*/
public class TraficLight extends Applet
implements ItemListener
{
CheckboxGroup cg1 = new CheckboxGroup ();
public void init()
{
Checkbox c1,c2,c3;
setBackground(Color.black);
c1=new Checkbox ("RED", cg1, false);
c1.setBackground(Color.red);
c2=new Checkbox ("GREEN", cg1, false);
c2.setBackground(Color.green);
c3=new Checkbox ("YELLOW", cg1, false);
c3.setBackground(Color.yellow);
c1.addItemListener(this);
c2.addItemListener(this);

27
Java Programming Lab II B.Tech II sem. R18

c3.addItemListener(this);
add (c1);
add (c2);
add (c3);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
Checkbox chk = cg1.getSelectedCheckbox();
if(chk.getLabel()=="YELLOW")
{
g.setColor(Color.yellow);
g.drawString(chk.getLabel() + " is selected : READY TO GO", 10 ,70);
}
if(chk.getLabel()=="RED")
{
g.setColor(Color.red);
g.drawString(chk.getLabel() + " is selected : STOP", 10 ,70);
}
if(chk.getLabel()=="GREEN")
{ g.setColor(Color.green);
g.drawString(chk.getLabel() + " is selected : GO ", 10 ,70);
}
g.fillOval(10,100,50,50);
}
}

28
Java Programming Lab II B.Tech II sem. R18

OUTPUT:

29
Java Programming Lab II B.Tech II sem. R18

Program 8:
Write a java program to create an abstract class named Shape that contains two integers
and empty method named printArea() Provide three classes named rectangle,triangle and
circle such that each one of the classes extends the class shape each one of the classes
contains only the method printarea() that prints the area of the given shape
abstract class shape
{
int l,b;
abstract public void printArea();
}
class rectangle extends shape
{
rectangle(int l,int b)
{
super.l=l;
super.b=b;
}
public void printArea()
{
System.out.println("area of rectangle is: "+l*b);
}
}
class triangle extends shape
{
triangle(int l,int b)
{
super.l=l;
super.b=b;
}
public void printArea()
{
System.out.println("area of triangle is: "+05.*l*b*b);
}
}
30
Java Programming Lab II B.Tech II sem. R18

class circle extends shape


{
int r;
circle(int r)
{
this.r=r;
}
public void printArea()
{
System.out.println("area of circle is: "+22.7*r*r);
}
}
class shape1Demo
{
public static void main(String[] a)
{
rectangle ob1=new rectangle(10,20);
triangle ob2=new triangle(10,20);
circle ob3=new circle(20);
ob1.printArea();
ob2.printArea();
ob3.printArea();
}
}

31
Java Programming Lab II B.Tech II sem. R18

OUTPUT:

32
Java Programming Lab II B.Tech II sem. R18

Program 9:

Suppose that a table named Table.txt is stored in a text file. The first line in the file is the
header, and the remaining lines correspond to rows in the table. The elements are
seperated by commas. Write a java program to display the table using Labels in Grid
Layout.
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;
public class JTableDemo extends JApplet
{
public void init( )
{
Container c =getContentPane( );
c.setLayout(new BorderLayout( ));
String fields [ ]={"empid "," empname ","empsal"} ;
Object details [][] = {{" 1" ,"Nataraj" ,"4500.50 "} , {"2","ravi" ," 4567.50 "} ,
{"3","raja","2246.30"},{"4","sita","3245.75"},
{"5"," Jyostna " ,"2500.25"}
} ;
JTable jt = new JTable( details, fields ) ;
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED ; // if the rows are more than
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ; // height of the applet,
JScrollPanejsp = new JScrollPane(jt); // scroll bar is added
c.add(jsp , BorderLayout.SOUTH ) ;
}
}
/*
<APPLET ALIGN="CENTER" CODE="JTableDemo.class" WIDTH=500
HEIGHT=500></APPLET>
*/

33
Java Programming Lab II B.Tech II sem. R18

OUTPUT:

34
Java Programming Lab II B.Tech II sem. R18

Program 10:

Write a java program that handles all mouse events and shows the event name at the center
of the window when a mouse event is fired(Use Adapter classes)

import java.awt.event.*;
import java.awt.*;
import java.applet.*;
public class MouseEv1 extends Applet
{
String msg="welcome";
public void init()
{
addMouseListener(new InnerCls1());
addMouseMotionListener(new InnerCls2());
}
public void paint(Graphics g)
{
Dimension d=getSize();
g.drawString(msg,(getWidth()/2)-msg.length()/2,(getHeight()/2));
}
class InnerCls2 extends MouseMotionAdapter
{
public void mouseMoved(MouseEvent me)
{
msg="mouseMoved"+me.getX()+"'"+me.getY();
repaint();
}

35
Java Programming Lab II B.Tech II sem. R18

public void mouseDragged(MouseEvent me)


{
msg="mouseDragged"+me.getX()+"'"+me.getY();
repaint();
}
}
class InnerCls1 extends MouseAdapter
{
public void mouseClicked(MouseEvent me)
{
msg="Mouse Clicked at "+me.getX()+"'"+me.getY();
repaint();
}
public void mousePressed(MouseEvent me)
{
msg="Mouse Pressed at "+me.getX()+"'"+me.getY();
repaint();
}
public void mouseReleased(MouseEvent me)
{
msg="Mouse released at "+me.getX()+"'"+me.getY();
repaint();
}
public void mouseEntered(MouseEvent me)
{
msg="mouseEntered"+me.getX()+"'"+me.getY();
repaint();
36
Java Programming Lab II B.Tech II sem. R18

}
public void mouseExited(MouseEvent me)
{
msg="mouseExited"+me.getX()+"'"+me.getY();
repaint();
}
}
}
/*
<applet code="MouseEv1" height=500 width=500></applet>
*/
OUTPUT:

37
Java Programming Lab II B.Tech II sem. R18

38
Java Programming Lab II B.Tech II sem. R18

39
Java Programming Lab II B.Tech II sem. R18

40
Java Programming Lab II B.Tech II sem. R18

Program 11:
Write a java program that loads names and phone numbers from the text file where data is
organized as one line per record and each field in record are separated by a tab(\t).It takes
a name or phone number as input and prints corresponding other value from hash
table(hint: use Hash Table)
import java.util.*;
import java.io.*;
public class Hashtbl {
public static void main(String[] args)
{
try
{
FileInputStream fs = new FileInputStream("D:\\ph.txt");
Scanner sc = new Scanner(fs).useDelimiter("\\s+");
Hashtable<String, String> ht = new Hashtable<String, String>();
String[] arrayList;
String a;
System.out.println("HASH TABLE IS");
System.out.println("--------------------------");
System.out.println("KEY : VALUE");
while (sc.hasNext())
{
a = sc.nextLine();
arrayList = a.split("\\s+");
ht.put(arrayList[0], arrayList[1]);
System.out.println(arrayList[0] + ":" + arrayList[1]);
}

41
Java Programming Lab II B.Tech II sem. R18

System.out.println("----MENU------");
System.out.println("----1.Search by Name------");
System.out.println("----2.Search by Mobile------");
System.out.println("----3.Exit------");
String opt = "";
String name, mobile;
Scanner s = new Scanner(System.in);
while (opt != "3")
{
System.out.println("Enter Your Option 1,2,3");
opt = s.next();
switch (opt)
{
case "1":
System.out.println("Enter Name");
name = s.next();
if (ht.containsKey(name))
{
System.out.println("Mobile is " + ht.get(name));
}
else
{
System.out.println("Not Found");
}
break;

42
Java Programming Lab II B.Tech II sem. R18

case "2":
System.out.println("Enter mobile");
mobile = s.next();
if (ht.containsValue(mobile)) {
for (Map.Entry e : ht.entrySet()) {
if (mobile.equals(e.getValue())) {
System.out.println("Name is " + e.getKey());
}
}
} else {
System.out.println("Not Found");
}
}
break;
case "3": {
opt = "3";
System.out.println("Menu Successfully Exited");
}
break;
default:
System.out.println("Choose Option betwen 1 and Three");
break;
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}}}
43
Java Programming Lab II B.Tech II sem. R18

OUTPUT:
HASH TABLE IS
KEY : VALUE
PRA 1236

RAP 2034

----MENU------
----1.Search by Name------
----2.Search by Mobile------
----3.Exit------
Enter Your Option 1,2,3
1
Enter Name: PRA
Mobile is 1236
Enter Your Option 1,2,3
2

Enter mobile 2034


Name is RAP

Program 12:
44
Java Programming Lab II B.Tech II sem. R18

Write a Java program that correctly implements the producer – consumer problem using
the concept of interthread communication.

class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try

45
Java Programming Lab II B.Tech II sem. R18

{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
this.n=n;
valueSet=true;
System.out.println("Put:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
46
Java Programming Lab II B.Tech II sem. R18

}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
class ProdCons
{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-c to stop");
}
}

47
Java Programming Lab II B.Tech II sem. R18

Output:
Put:1
Got:1
Put:2
Got:2
Put:3
Got:3
Put:4
Got:4
Put:5
Got:5
Put:6
Got:6
Put:7
Got:7
Put:8
Got:8
Put:9
Got:9
Put:10
Got:10

48
Java Programming Lab II B.Tech II sem. R18

Program 13:

Write a Java program to list all the files in a directory including the files present in all its
subdirectories.

import java.io.File;
public class ListDirectoryRecurisve {
public void listDirectory(String dirPath, int level) {
File dir = new File(dirPath);
File[] firstLevelFiles = dir.listFiles();
if (firstLevelFiles != null && firstLevelFiles.length > 0) {
for (File aFile : firstLevelFiles) {
for (int i = 0; i < level; i++) {
System.out.print("\t");
}
if (aFile.isDirectory()) {
System.out.println("[" + aFile.getName() + "]");
listDirectory(aFile.getAbsolutePath(), level + 1);
} else {
System.out.println(aFile.getName());
}
}
}
}
public static void main(String[] args) {
ListDirectoryRecurisve test = new ListDirectoryRecurisve();
String dirToList = System.getProperty("user.home") + File.separator + "Documents";
test.listDirectory(dirToList, 0);
}}

49

You might also like