New Java Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 43

x1. Use Eclipse or Net bean 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.

Procedure
Step 1 - Install JDK in the computer.
Step 2 - Set the path in the Environment Variables from Advanced Setting of computer
Step 3 - Download Eclipse from Eclipse website
Step 4 - Install the Eclipse (follow the screen to install eclipse)

Select the sultable version based on your OS.

Then download get starts.


Double click on the Eclipse Application.

Click on Run in the Security Warning box.


Then, the installation process begins.

Click on Eclipse IDE for Java Developers.


Click on Install button.
Click on Accept Now.

Then the Eclipse installation begins.


Click on Accept
Click on Select All and Accept Selected.
After completing, click on Launch to start the Eclipse IDE.

Creating Project and Classes in Eclipse IDE


Browse the Workspace for storing the java project and click on Launch.
Select "Create a new Java project".

Type the project name and click on Finish.


Now, create the class in src directory from Package Explorer window.

Type the class name and click on Finish.


Type the java code.

Click on Play button to run or execute the java code.


EXPERIMENT 2:
2. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the
digits and for the +, -,*, % operations. Add a text field to display the result. Handle any possible
exceptions like divided by zero.

import java.awt.*;
import java.awt.Event.*;
import javax.Swing.*;
class BuildCalculator extends JFrame implements ActionListener
{
JFrame actualWindow;
JPanel resultPanel, buttonPanel, infoPanel;
JTextField resultTxt;
JButton btn_digits[] = new JButton[10];
JButton btn_plus, btn_minus, btn_mul, btn_div, btn_equal, btn_dot, btn_clear;
char eventFrom;
JLabel expression, appTitle, siteTitle ;
double oparand_1 = 0, operand_2 = 0;
String operator = "=";
BuildCalculator()
{
Font txtFont = new Font("SansSerif", Font.BOLD, 20);
Font titleFont = new Font("SansSerif", Font.BOLD, 30);
Font expressionFont = new Font("SansSerif", Font.BOLD, 15);
actualWindow = new JFrame("Calculator");
resultPanel = new JPanel();
buttonPanel = new JPanel();
infoPanel = new JPanel();
actualWindow.setLayout(new GridLayout(3, 1));
buttonPanel.setLayout(new GridLayout(4, 4));
infoPanel.setLayout(new GridLayout(3, 1));
actualWindow.setResizable(false);
appTitle = new JLabel("My Calculator");
appTitle.setFont(titleFont);
expression = new JLabel("Expression shown here");
expression.setFont(expressionFont);
siteTitle = new JLabel("www.btechsmartclass.com");
siteTitle.setFont(expressionFont);
siteTitle.setHorizontalAlignment(SwingConstants.CENTER);
siteTitle.setForeground(Color.BLUE);
resultTxt = new JTextField(15);
resultTxt.setBorder(null);
resultTxt.setPreferredSize(new Dimension(15, 50));
resultTxt.setFont(txtFont);
resultTxt.setHorizontalAlignment(SwingConstants.RIGHT);
for(int i = 0; i < 10; i++)
{
btn_digits[i] = new JButton(""+i);
btn_digits[i].addActionListener(this);
}
btn_plus = new JButton("+");
btn_plus.addActionListener(this);
btn_minus = new JButton("-");
btn_minus.addActionListener(this);
btn_mul = new JButton("*");
btn_mul.addActionListener(this);
btn_div = new JButton("/");
btn_div.addActionListener(this);
btn_dot = new JButton(".");
btn_dot.addActionListener(this);
btn_equal = new JButton("=");
btn_equal.addActionListener(this);
btn_clear = new JButton("Clear");
btn_clear.addActionListener(this);

resultPanel.add(appTitle);
resultPanel.add(resultTxt);
resultPanel.add(expression);
for(int i = 0; i < 10; i++) {
buttonPanel.add(btn_digits[i]);
}
buttonPanel.add(btn_plus);
buttonPanel.add(btn_minus);
buttonPanel.add(btn_mul);
buttonPanel.add(btn_div);
buttonPanel.add(btn_dot);
buttonPanel.add(btn_equal);
infoPanel.add(btn_clear);
infoPanel.add(siteTitle);
actualWindow.add(resultPanel);
actualWindow.add(buttonPanel);
actualWindow.add(infoPanel);
actualWindow.setSize(300, 500);
actualWindow.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e)
{
eventFrom = e.getActionCommand().charAt(0);
String buildNumber;
if(Character.isDigit(eventFrom))
{
buildNumber = resultTxt.getText() + eventFrom;
resultTxt.setText(buildNumber);
}
else if(e.getActionCommand() == ".")
{
buildNumber = resultTxt.getText() + eventFrom;
resultTxt.setText(buildNumber);
}
else if(eventFrom != '=')
{
oparand_1 = Double.parseDouble(resultTxt.getText());
operator = e.getActionCommand();
expression.setText(oparand_1 + " " + operator);
resultTxt.setText("");
}
else if(e.getActionCommand() == "Clear")
{
resultTxt.setText("");
}
else
{
operand_2 = Double.parseDouble(resultTxt.getText());
expression.setText(expression.getText() + " " + operand_2);
switch(operator)
{
case "+": resultTxt.setText(""+(oparand_1 + operand_2)); break;
case "-": resultTxt.setText(""+(oparand_1 - operand_2)); break;
case "*": resultTxt.setText(""+(oparand_1 * operand_2)); break;
case "/":
try
{
if(operand_2 == 0)
throw new ArithmeticException();
resultTxt.setText(""+(oparand_1 / operand_2));
break;
}
catch(ArithmeticException ae)
{
JOptionPane.showMessageDialog(actualWindow, "Divisor can not be ZERO");
}
}
}
}
}
public class Calculator
{
public static void main(String[] args)
{
new BuildCalculator();
}
}

Result:
EXPERIMENT 3:

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


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.
A) Develop an applet in Java that displays a simple message.

import java.awt.*;
import java.applet.*;
/* <applet code="Applet1" width=200 height=300></applet>*/
public class AppletExample extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello World!",20,20);
}
}

Result:

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.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*<applet code="Fact.class" height=300 width=300></applet>*/
public class Factorial extends Applet implements ActionListener
{
Label inputLable,outputLable;
TextField inputTextField,outputTextField;
Button btn;
public void init()
{
inputLable=new Label("Enter any integer value: ");
inputTextField=new TextField(5);
btn=new Button("Compute");
btn.addActionListener(this);
outputLable=new Label("Factorial of given integer number is ");
outputTextField=new TextField(10);
add(inputLable);
add(inputTextField);
add(btn);
add(outputLable);
add(outputTextField);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btn)
{
int fact=fact(Integer.parseInt(inputTextField.getText()));
outputTextField.setText(String.valueOf(fact));
}
}
int fact(int f)
{
if(f==0)
return 1;
else
return f*fact(f-1);
}
}

Result:
EXPERIMENT 4:
Write a Java program that creates a user interface to perform integer divisions. The user enters two
numbers in the text fields, Num1 and Num2. The division of Num1 and Num 2 is displayed in the
Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program
would throw a Number Format Exception. If Num2 were Zero, the program would throw an
Arithmetic Exception. Display the exception in a message dialog box.

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

class BuildGUI extends JFrame implements ActionListener


{
JFrame actualWindow;
JPanel container;
JTextField txt_num1, txt_num2, txt_result;
JButton btn_div;
BuildGUI()
{
actualWindow = new JFrame("Experiment 4");
container = new JPanel();
container.setLayout(new FlowLayout());
txt_num1 = new JTextField(20);
txt_num2 = new JTextField(20);
txt_result = new JTextField(20);
btn_div = new JButton("Divide");
btn_div.addActionListener(this);
container.add(txt_num1);
container.add(txt_num2);
container.add(btn_div);
container.add(txt_result);
actualWindow.add(container);
actualWindow.setSize(300, 300);
actualWindow.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e)
{
int num1, num2;
try
{
num1 = Integer.parseInt(txt_num1.getText());
num2 = Integer.parseInt(txt_num2.getText());
txt_result.setText(num1/num2+"");
}
catch(NumberFormatException nfe)
{
JOptionPane.showMessageDialog(actualWindow,"Please do enter only integers");
}
catch(ArithmeticException ae)
{
JOptionPane.showMessageDialog(actualWindow,"Divisor can not be ZERO");
}
}
}
public class Experiment_4
{
public static void main(String[] args)
{
new BuildGUI();

Result:

EXPERIMENT 5:
Write a Java program that implements a multi-thread application that has three threads. First thread
generates a random integer every 1 second and if the value is even, the second thread computes the
square of the number and prints. If the value is odd, the third thread will print the value of the cube of
the number.

import java.util.Random;
class RandomNumberThread extends Thread
{
public void run()
{
Random random = new Random();
for (int i = 0; i < 10; i++)
{
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " + randomInteger);
if((randomInteger%2) == 0)
{
SquareThread sThread = new SquareThread(randomInteger);
sThread.start();
}
else
{
CubeThread cThread = new CubeThread(randomInteger);
cThread.start();
}
try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
System.out.println(ex);
}
}
}
}
class SquareThread extends Thread
{
int number;
SquareThread(int randomNumbern)
{
number = randomNumbern;
}
public void run()
{
System.out.println("Square of " + number + " = " + (number * number));
}
}
class CubeThread extends Thread
{
int number;
CubeThread(int randomNumber)
{
number = randomNumber;
}
public void run()
{
System.out.println("Cube of " + number + " = " + number * number * number);
}
}
public class MultiThreadingTest
{
public static void main(String args[])
{
RandomNumberThread rnThread = new RandomNumberThread();
rnThread.start();
}
}

Result:
EXPERIMENT 6:
Write a Java program for the following:
Create a doubly linked list of elements. Delete a given element from the above list.
Display the contents of the list after deletion.
import java.util.*;
public class DoublyLinkListDemo
{
public static void main(String[] args)
{
int i,ch,element,position;
LinkedList<Integer> dblList = new LinkedList<Integer>();
System.out.println("1.Insert element at begining");
System.out.println("2.Insert element at end");
System.out.println("3.Insert element at position");
System.out.println("4.Delete a given element");
System.out.println("5.Display elements in the list");
System.out.println("6.Exit");
Scanner sc=new Scanner(System.in);
do {
System.out.print("Choose your choice(1 - 6) :");
ch=sc.nextInt();
switch(ch) {
case 1: // To read element form the user
System.out.print("Enter an element to insert at begining : ");
element=sc.nextInt();
// to add element to doubly linked list at begining
dblList.addFirst(element);
System.out.println("Successfully Inserted");
break;
case 2: // To read element form the user
System.out.print("Enter an element to insert at end : ");
element=sc.nextInt();
// to add element to doubly linked list at end
dblList.addLast(element);
System.out.println("Successfully Inserted");
break;
case 3: // To read position form the user
System.out.print("Enter position to insert element : ");
position=sc.nextInt();
// checks if the position is lessthan or equal to list size.
if(position<=dblList.size()) {
// To read element
System.out.print("Enter element : ");
element=sc.nextInt();
// to add element to doubly linked list at given position
dblList.add(position,element);
System.out.println("Successfully Inserted");
}
else {
System.out.println("Enter the size between 0 to"+dblList.size());
}
break;
case 4: // To read element form the user to remove
System.out.print("Enter element to remove : ");
Integer ele_rm;
ele_rm=sc.nextInt();
if (dblList.contains(ele_rm)){
dblList.remove(ele_rm);
System.out.println("Successfully Deleted");
Iterator itr=dblList.iterator();
System.out.println("Elements after deleting :"+ele_rm);
while(itr.hasNext()) {
System.out.print(itr.next()+"<->");
}
System.out.println("NULL");
}
else {
System.out.println("Element not found");
}
break;

case 5: // To Display elements in the list


Iterator itr=dblList.iterator();
System.out.println("Elements in the list :");
while(itr.hasNext()) {
System.out.print(itr.next()+"<->");
}
System.out.println("NULL");
break;

case 6: System.out.println("Program terminated");


break;
default:System.out.println("Invalid choice");
}
}
while(ch!=6);
}
}

Output:

EXPERIMENT 7:
Write a Java program that simulates a traffic light. The program lets the user select one of three lights: red,
yellow, or green with radio buttons. On selecting a button, an appropriate message with “Stop” or “Ready” or
“Go” should appear above the buttons in the selected color. Initially, there is no message shown.

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class TrafficLightSimulator extends JFrame implements ItemListener {
JLabel lbl1, lbl2;
JPanel nPanel, cPanel;
CheckboxGroup cbg;
public TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setSize(600,400);
setLayout(new GridLayout(2, 1));
nPanel = new JPanel(new FlowLayout());
cPanel = new JPanel(new FlowLayout());
lbl1 = new JLabel();
Font font = new Font("Verdana", Font.BOLD, 70);
lbl1.setFont(font);
nPanel.add(lbl1);
add(nPanel);
Font fontR = new Font("Verdana", Font.BOLD, 20);
lbl2 = new JLabel("Select Lights");
lbl2.setFont(fontR);
cPanel.add(lbl2);
cbg = new CheckboxGroup();
Checkbox rbn1 = new Checkbox("Red Light", cbg, false);
rbn1.setBackground(Color.RED);
rbn1.setFont(fontR);
cPanel.add(rbn1);
rbn1.addItemListener(this);
Checkbox rbn2 = new Checkbox("Orange Light", cbg, false);
rbn2.setBackground(Color.ORANGE);
rbn2.setFont(fontR);
cPanel.add(rbn2);
rbn2.addItemListener(this);
Checkbox rbn3 = new Checkbox("Green Light", cbg, false);
rbn3.setBackground(Color.GREEN);
rbn3.setFont(fontR);
cPanel.add(rbn3);
rbn3.addItemListener(this);
add(cPanel);
setVisible(true);
// to close the main window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// To read selected item
public void itemStateChanged(ItemEvent i) {
Checkbox chk = cbg.getSelectedCheckbox();
String str=chk.getLabel();
char choice=str.charAt(0);
switch (choice) {
case 'R':lbl1.setText("STOP");
lbl1.setForeground(Color.RED);
break;

case 'O':lbl1.setText("READY");
lbl1.setForeground(Color.ORANGE);
break;
case 'G':lbl1.setText("GO");
lbl1.setForeground(Color.GREEN);
break;
}
}
// main method
public static void main(String[] args) {
new TrafficLightSimulator();
}
}

Output:
EXPERIMENT 8:
Write a Java program to create an abstract class named Shape that contains two integers and an empty
method named print Area (). 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 print
Area () that prints the area of the given shape.

import java.util.*;
abstract class Shape {
public int x,y;
public abstract void printArea();
}
class Rectangle1 extends Shape {
public void printArea() {
float area;
area= x * y;
System.out.println("Area of Rectangle is " +area);
}
}
class Triangle extends Shape {
public void printArea() {
float area;
area= (x * y) / 2.0f;
System.out.println("Area of Triangle is " + area);
}
}
class Circle extends Shape {
public void printArea() {
float area;
area=(22 * x * x) / 7.0f;
System.out.println("Area of Circle is " + area);
}
}
public class AreaOfShapes {
public static void main(String[] args) {
int choice;
Scanner sc=new Scanner(System.in);
System.out.println("Menu \n 1.Area of Rectangle \n 2.Area of Traingle \n 3.Area of Circle ");
System.out.print("Enter your choice : ");
choice=sc.nextInt();
switch(choice) {
case 1: System.out.println("Enter length and breadth for area of rectangle : ");
Rectangle1 r = new Rectangle1();
r.x=sc.nextInt();
r.y=sc.nextInt();
r.printArea();
break;
case 2: System.out.println("Enter bredth and height for area of traingle : ");
Triangle t = new Triangle();
t.x=sc.nextInt();
t.y=sc.nextInt();
t.printArea();
break;
case 3: System.out.println("Enter radius for area of circle : ");
Circle c = new Circle();
c.x = sc.nextInt();
c.printArea();
break;
default:System.out.println("Enter correct choice");
}
}
}

Output:

EXPERIMENT 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 separated by commas. Write a
java program to display the table using Labels in Grid Layout.

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Text_To_Table extends JFrame
{
public void convertTexttotable()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
GridLayout g = new GridLayout(0, 4);
setLayout(g);
try
{
FileInputStream fis = new FileInputStream("./Table.txt");
Scanner sc = new Scanner(fis);
String[] arrayList;
String str;
while (sc.hasNextLine())
{
str = sc.nextLine();
arrayList = str.split(",");
for (String i : arrayList)
{
add(new Label(i));
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
setVisible(true);
setTitle("Display Data in Table");
}
}
public class TableText
{
public static void main(String[] args)
{
Text_To_Table tt = new Text_To_Table();
tt.convertTexttotable();
}
}
Table.txt

NAME,NUMBER,MARKS,RESULT
NAVEEN,501,544,PASS
RAMESH,503,344,PASS
DURGA,521,344,PASS
ASHOK,532,344,PASS
MADHU,543,344,PASS

Output:

EXPERIMENT 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 javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class MouseEventPerformer extends JFrame implements MouseListener
{
JLabel l1;
public MouseEventPerformer()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setLayout(new FlowLayout(FlowLayout.CENTER));
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
l1.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
l1.setText("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
l1.setText("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
l1.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
l1.setText("Mouse Clicked");
}
public static void main(String[] args) {
MouseEventPerformer mep = new MouseEventPerformer();
}
}

Output:
EXPERIMENT 11:
Write a Java program that loads names and phone numbers from a text file where the data is
organized as one line per record and each field in a record are separated by a tab (\t). It takes a name
or phone number as input and prints the corresponding other value from the hash table (hint: use hash
tables).

Source code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
public class HashTab
{
public static void main(String[] args)
{
HashTab prog11 = new HashTab();
Hashtable hashData = prog11.readFromFile("HashTab.txt");
System.out.println("File data into Hashtable:\n" + hashData);
prog11.printTheData(hashData, "raja");

prog11.printTheData(hashData, "123");
prog11.printTheData(hashData, "----");
}
private void printTheData(Hashtable hashData, String input)
{
String output = null; if (hashData != null)
{
Set keys = hashData.keySet();
if (keys.contains(input))
{
output = hashData.get(input);
}
else
{
Iterator iterator = keys.iterator();
while (iterator.hasNext())
{
String key = iterator.next();
String value = hashData.get(key);
if (value.equals(input))
{
output = key; break;
}
}
}
}
System.out.println("Input given:" + input);
if (output != null)
{
System.out.println("Data found in HashTable:" + output);
}
else
{
System.out.println("Data not found in HashTable");
}
}
private Hashtable readFromFile(String fileName)
{
Hashtable hashData = new Hashtable();
try
{
File f = new File("D:\\java\\" + fileName);
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null; while ((line = br.readLine()) != null)
{
String[] details = line.split("\t");
hashData.put(details[0], details[1]);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return hashData;
}
}

OUTPUT:
java.io.FileNotFoundException: D:\java\HashTab.txt (The system cannot find the file
specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at HashTab.readFromFile(HashTab.java:61)
at HashTab.main(HashTab.java:14)
File data into Hashtable:
{}
Input given:raja
Data not found in HashTable
Input given:123
Data not found in HashTable
Input given:----
Data not found in HashTable

EXPERIMENT 12:
Write a Java program that correctly implements the producer – consumer problem using the
concept of interthread communication.
Source Code:

class ItemQueue
{
int item; boolean valueSet = false; synchronized int getItem()
{
while (!valueSet)
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Consummed:" + item);
valueSet = false; try { Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
notify();
return item;
}
synchronized void putItem(int item)
{
while (valueSet)
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.item = item; valueSet = true; System.out.println("Produced: " + item);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
notify();
}
}
class Producer implements Runnable
{
ItemQueue itemQueue;
Producer(ItemQueue itemQueue)
{
this.itemQueue = itemQueue;
new Thread(this, "Producer").start();
}
public void run() { int i = 0;
while(true)
{
itemQueue.putItem(i++);
}
}
}
class Consumer implements Runnable
{
ItemQueue itemQueue;
Consumer(ItemQueue itemQueue)
{
this.itemQueue = itemQueue;
new Thread(this, "Consumer").start();
}
public void run()
{
while(true)
{
itemQueue.getItem();
}
}
}
class ProducerConsumer
{
public static void main(String args[])
{
ItemQueue itemQueue = new ItemQueue();
new Producer(itemQueue);
new Consumer(itemQueue);
}
}
Output:

OUTPUT:
Produced: 0
Consummed:0
Produced: 1
Consummed:1
Produced: 2
Consummed:2
Produced: 3
Consummed:3
Produced: 4
Consummed:4
Produced: 5
Consummed:5
Produced: 6
Consummed:6
Produced: 7
Consummed:7
Produced: 8
Consummed:8
Produced: 9
Consummed:9
Produced: 10
Consummed:10
Produced: 11
Consummed:11
Produced: 12
Consummed:12
Produced: 13
Consummed:13
Produced: 14
Consummed:14
Produced: 15
Consummed:15
Produced: 16
Consummed:16
Produced: 17
Consummed:17
Produced: 18
Consummed:18
Produced: 19
Consummed:19
Produced: 20
Consummed:20
Produced: 21
Consummed:21
Produced: 22
Consummed:22
Produced: 23
Consummed:23
Produced: 24
Consummed:24
Produced: 25
Consummed:25
Produced: 26
Consummed:26
Produced: 27
Consummed:27
Ect…..

EXPERIMENT 13:
Write a Java program to list all the files in a directory including the files present in all its
subdirectories

import java.util.Scanner;
import java.io.*;
public class ListingFiles
{
public static void main(String[] args)
{
String path = null; Scanner read = new Scanner(System.in);
System.out.print("Enter the root directory name: ");
path = read.next() + ":\\"; File f_ref = new File(path);
if (!f_ref.exists())
{
printLine();
System.out.println("Root directory does not exists!");
printLine();
}
else
{
String ch = "y"; while (ch.equalsIgnoreCase("y"))
{
printFiles(path);
System.out.print("Do you want to open any sub-directory (Y/N): ");
ch = read.next().toLowerCase();
if (ch.equalsIgnoreCase("y"))
{
System.out.print("Enter the sub-directory name: ");
path = path + "\\\\" + read.next(); File f_ref_2 = new File(path);
if (!f_ref_2.exists())
{
printLine();
System.out.println("The sub-directory does not exists!");
printLine();
int lastIndex = path.lastIndexOf("\\"); path = path.substring(0, lastIndex);
}
}
}
}
System.out.println("***** Program Closed *****");
}
public static void printFiles(String path)
{
System.out.println("Current Location: " + path);
File f_ref = new File(path);
File[] filesList = f_ref.listFiles();
for (File file : filesList)
{
if (file.isFile())
System.out.println("- " + file.getName());
else System.out.println("> " + file.getName());
}
}
public static void printLine()
{
System.out.println("----------------------------------------");
}
}

OUTPUT:

Enter the root directory name: windpws


----------------------------------------
Root directory does not exists!
----------------------------------------
***** Program Closed *****

You might also like