Sunday, December 20, 2009
To create Bank software using Java
import java.lang.*;
class Bank
{
double bal,damt,wamt;
String acct_type, acct_name;
int acctno;
void initial(int no, String type,String name,double balance)
{
acctno=no;
acct_type=type;
acct_name=name;
bal=balance;
}
void deposit(double amt)
{
damt=amt;
bal=bal+damt;
System.out.println("Amount Deposited: "+damt);
}
void withdraw(double at)
{
wamt=at;
if(bal>wamt)
{
bal=bal-wamt;
System.out.println("Amount Withdrawn: "+wamt);
}
else
{
System.out.println("Withdrawn Amount greater than balance \n Balance :"+bal);
}
}
void display()
{
System.out.println("Account Number: "+acctno);
System.out.println("Account Type: "+acct_type);
System.out.println("Account Name: "+acct_name);
System.out.println("Account Balance: "+bal);
}
}
class BankDemo
{
public static void main(String args[])throws IOException
{
DataInputStream in=new DataInputStream(System.in);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String name,type;
int no,choice,i;
double ba,wa,da;
boolean baless=false;
i=0;
System.out.print("Enter account number: ");
no=Integer.parseInt(in.readLine());
System.out.print("Enter account type: ");
type=br.readLine();
System.out.print("Enter account name: ");
name=br.readLine();
do{
System.out.print("Enter account balance: ");
ba=Double.parseDouble(in.readLine());
if(ba<1000)
{
baless=true;
System.out.println("Minimum balance must be Rs.1000");
}
else
baless=false;
}while(baless==true);
Bank b1=new Bank();
b1.initial(no,type,name,ba);
while(i==0)
{
System.out.print("1.Deposit\n2.Withdraw\n3.Display\n4.Exit\nEnter Choice: ");
choice=Integer.parseInt(in.readLine());
switch(choice)
{
case 1:System.out.print("Enter amount to be deposited: ");
da=Double.parseDouble(in.readLine());
b1.deposit(da);
break;
case 2:System.out.print("Enter amount to be withdrawn: ");
wa=Double.parseDouble(in.readLine());
b1.withdraw(wa);
break;
case 3:b1.display();
break;
case 4:i=1;
break;
default: System.out.println("Not a vaild choice.");
}
}
}
}
Software to add, delete and print an item in shopping list in java
import java.io.DataInputStream; // to load DataInputStream class
class P34
{
public static void main(String args[ ])
{
Vector v = new Vector(5,2);
int count=0,i,choice, position;
String str = new String();
boolean flag = false;
String ans = "yes";
DataInputStream in = new DataInputStream(System.in);
count =args.length;
for(i=0;i
v.addElement(args[i]);
try
{
System.out.println("\n*********** Super Market **********\n");
do
{
System.out.println("\nSelect Any option (1 to 5)");
System.out.println("\t1. Delete an item ");
System.out.println("\t2. Add an item at a specific location ");
System.out.println("\t3. Add an item at the end of the list ");
System.out.println("\t4. Display Shopping List ");
System.out.println("\t5. Exit ");
choice = Integer.parseInt(in.readLine());
System.out.println();
switch(choice)
{
case 1:
/* Delete an Item */
System.out.print("Enter the item which you want to delete from shopping list : ");
str = in.readLine();
flag = v.removeElement(str);
if(flag==false)
System.out.println(" Item is not in the shopping list");
break;
case 2:
/* Add an item at a specific location */
System.out.print("Enter the item which you want to add in shopping list : ");
str = in.readLine();
System.out.print("Enter a specific location where you want to add an item : ");
position = Integer.parseInt(in.readLine());
v.insertElementAt(str,position-1);
break;
case 3:
/* Add an item at the end of the list */
System.out.print("Enter the item which you want to add in shopping list : ");
str = in.readLine();
v.addElement(str);
break;
case 4:
/* Display Shopping List */
Enumeration vEnum = v.elements();
System.out.println("\nItems in Shopping list are:");
while(vEnum.hasMoreElements())
System.out.println("\t"+vEnum.nextElement() +" ");
//System.out.println();
break;
default:
System.exit(0);
}
System.out.print("Do you Want to continue ? (Yes/No) : ");
ans=in.readLine();
}while(ans.equalsIgnoreCase("yes"));
}
catch(Exception e) { System.out.println("I/O Error"); }
}
}
To Develop a Java project for Server Test
import java.io.*;
import java.net.*;
public class servertest
{
final static int SERVER_PORT = 8001;
public static void main(String a[])
{
Server server;
String creq,sr;
BufferedReader reader,read;
PrintWriter writer,write;
server = new Server(SERVER_PORT);
reader = new BufferedReader(new InputStreamReader(server.in));
writer = new PrintWriter(new OutputStreamWriter(server.out),true);
read = new BufferedReader(new InputStreamReader(System.in));
write = new PrintWriter(new OutputStreamWriter(System.out),true);
writer.println("Java Test Server " + new Date());
while(true)
{
try {
creq = reader.readLine();
System.out.println("Client says : " + creq);
sr = read.readLine();
writer.println(sr);
/*if(creq.equals("hai"))
writer.println("i am venkatesh");*/
if(creq.equals("quit"))
System.exit(0);
}catch(IOException e) {
System.out.println("Exception caught");
}
}
}
}
class Server
{
private ServerSocket server;
private Socket socket;
public InputStream in;
public OutputStream out;
public Server(int port)
{
try {
server = new ServerSocket(port);
System.out.println("ServerSocket before accept : "+server);
System.out.println("Java test server on-line");
socket = server.accept();
System.out.println("ServerSocket after accept : "+server);
in = socket.getInputStream();
out = socket.getOutputStream();
}catch(IOException e) {
System.out.println("caught server constructor");
}
}
}
Calculator Application using Java
import java.awt.event.*;
public class my_calculator5
{
Font Bold=new Font("Helvetica", Font.BOLD, 20);
Label lcdDisplay = new Label("0",Label.RIGHT);
Label leftlcdDisplay = new Label("",Label.RIGHT);
Label rightlcdDisplay = new Label("",Label.RIGHT);
Button mem_recall=new Button("MR");
Button mem_clear=new Button("MC");
public void map_calculator()
{
event_handler e1=new event_handler();
Frame calc=new Frame("My Calculator :Beta version 5");
calc.setResizable(false);
calc.setSize(450,360);
calc.setBackground(Color.gray);
calc.setLayout(null);
//lcdDisplay.setEditable(false);not used for label
lcdDisplay.setBounds(68,58,320,30);
lcdDisplay.setFont(new Font("Helvetica", Font.PLAIN, 20));
lcdDisplay.setForeground(Color.orange);
lcdDisplay.setBackground(Color.black);
calc.add(lcdDisplay);
rightlcdDisplay.setBounds(388,58,30,30);
rightlcdDisplay.setFont(new Font("Helvetica", Font.PLAIN, 20));
rightlcdDisplay.setForeground(Color.green);
rightlcdDisplay.setBackground(Color.black);
calc.add(rightlcdDisplay);
//adding button 1 to 0
Button mplus=new Button("M+");
mplus.setBounds(72,96,60,34);
mplus.setBackground(Color.black);
mplus.setForeground(Color.red);
mplus.setFont(Bold);
mplus.addActionListener(e1);
calc.add(mplus);
mem_clear.setEnabled(false);
mem_clear.setBounds(136,96,60,34);
mem_clear.setBackground(Color.black);
mem_clear.setForeground(Color.red);
mem_clear.setFont(Bold);
mem_clear.addActionListener(e1);
calc.add(mem_clear);
mem_recall.setBounds(200,96,60,34);
mem_recall.setBackground(Color.black);
mem_recall.setForeground(Color.red);
mem_recall.setFont(Bold);
mem_recall.addActionListener(e1);
mem_recall.setEnabled(false);
calc.add(mem_recall);
Button one=new Button("1");
one.setBounds(72,134,60,34);
one.setBackground(Color.orange);
one.setFont(Bold);
one.addActionListener(e1);
calc.add(one);
Button two=new Button("2");
two.addActionListener(e1);
two.setBackground(Color.orange);
two.setBounds(136,134,60,34);
two.setFont(Bold);
calc.add(two);
Button three=new Button("3");
three.addActionListener(e1);
three.setBackground(Color.orange);
three.setBounds(200,134,60,34);
three.setFont(Bold);
calc.add(three);
Button four=new Button("4");
four.setBackground(Color.orange);
four.addActionListener(e1);
four.setFont(Bold);
four.setBounds(72,172,60,34);
calc.add(four);
Button five=new Button("5");
five.setBackground(Color.orange);
five.addActionListener(e1);
five.setFont(Bold);
five.setBounds(136,172,60,34);
calc.add(five);
Button six=new Button("6");
six.setBackground(Color.orange);
six.addActionListener(e1);
six.setFont(Bold);
six.setBounds(200,172,60,34);
calc.add(six);
Button seven=new Button("7");
seven.setBackground(Color.orange);
seven.addActionListener(e1);
seven.setFont(Bold);
seven.setBounds(72,210,60,34);
calc.add(seven);
Button eight=new Button("8");
eight.setBackground(Color.orange);
eight.addActionListener(e1);
eight.setFont(Bold);
eight.setBounds(136,210,60,34);
calc.add(eight);
Button nine=new Button("9");
nine.setBackground(Color.orange);
nine.addActionListener(e1);
nine.setFont(Bold);
nine.setBounds(200,210,60,34);
calc.add(nine);
Button zero=new Button("0");
zero.setBackground(Color.orange);
zero.addActionListener(e1);
zero.setFont(Bold);
zero.setBounds(136,248,60,34);
calc.add(zero);
//operation buttons
Button buttonDivide = new Button("/");
buttonDivide.setBackground(Color.blue);
buttonDivide.addActionListener(e1);
buttonDivide .setBounds(264,134,60,34);
buttonDivide .setForeground(Color.white);
buttonDivide .setFont(Bold);
calc.add(buttonDivide);
Button buttonMultiply = new Button("X");
buttonMultiply.setBackground(Color.blue);
buttonMultiply.addActionListener(e1);
buttonMultiply.setBounds(264,172,60,34);
buttonMultiply.setForeground(Color.white);
buttonMultiply.setFont(Bold);
calc.add(buttonMultiply);
Button buttonMinus = new Button("-");
buttonMinus.setBackground(Color.blue);
buttonMinus.addActionListener(e1);
buttonMinus.setBounds(264,210,60,34);
buttonMinus.setForeground(Color.white);
buttonMinus.setFont(Bold);
calc.add(buttonMinus);
Button buttonPlus= new Button("+");
buttonPlus.setBackground(Color.blue);
buttonPlus.addActionListener(e1);
buttonPlus.setBounds(264,248,60,34);
buttonPlus.setForeground(Color.white);
buttonPlus.setFont(Bold);
calc.add(buttonPlus);
Button buttonPoint= new Button(".");
buttonPoint.setBackground(Color.blue);
buttonPoint.addActionListener(e1);
buttonPoint.setBounds(200,248,60,34);
buttonPoint.setForeground(Color.white);
buttonPoint.setFont(Bold);
calc.add(buttonPoint);
Button buttonplusminus = new Button("+/-");
buttonplusminus .setBackground(Color.blue);
buttonplusminus.addActionListener(e1);
buttonplusminus.setBounds(72,248,60,34);
buttonplusminus.setForeground(Color.white);
buttonplusminus.setFont(Bold);
calc.add(buttonplusminus);
Button clear = new Button("C");
clear.setBackground(Color.red);
clear.addActionListener(e1);
clear.setBounds(328,134,60,34);
clear.setForeground(Color.white);
clear.setFont(Bold);
calc.add(clear);
Button percent = new Button("%");
percent.setBackground(Color.blue);
percent.addActionListener(e1);
percent.setBounds(328,172,60,34);
percent.setForeground(Color.white);
percent.setFont(Bold);
calc.add(percent);
Button oneoverx = new Button("1/x");
oneoverx.setBackground(Color.blue);
oneoverx.addActionListener(e1);
oneoverx .setBounds(328,210,60,34);
oneoverx .setForeground(Color.white);
oneoverx .setFont(Bold);
calc.add(oneoverx);
Button buttonequal = new Button("=");
buttonequal.setBackground(Color.green);
buttonequal.addActionListener(e1);
buttonequal.setBounds(328,248,60,34);
buttonequal.setForeground(Color.red);
buttonequal.setFont(Bold);
calc.add(buttonequal);
calc.setVisible(true);
}
public static void main(String args[])
{
my_calculator5 m1=new my_calculator5();
m1.map_calculator();
}
String temp="";
String sign="";
double result=1;//CHANGE MADE RESULT=0 BEFORE
double temp_minus=0;
boolean flag_minus_first=true;
boolean mul_flag=true;
double mul_temp=1;
double memory;
boolean memory_flag=false;
boolean divide_flag=true;
double divide_temp=1;
boolean mr_flag=false;///used for memory recall mechanism
boolean point_flag=true;
//boolean plus_slash_minus_flag=true;
private class event_handler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String cmd=e.getActionCommand();
System.out.println(cmd);
//**********************************************************************************************
if(cmd=="+/-")
{
//plus_slash_minus_flag=true means that user has pressed +/- sign when value from temp is displaying to lcd screen not from result varibable
if(temp!="" )//&& plus_slash_minus_flag==true && )
{
if(Double.parseDouble(temp)>0)
{
temp=("-"+ temp);
System.out.println("temp="+temp);
lcdDisplay.setText(temp);
}
else if(Double.parseDouble(temp)<0) { temp=temp.substring(1,temp.length()); System.out.println("temp="+temp); lcdDisplay.setText(temp); } //plus_slash_minus_flag=false; } //enters when user press +/- and value from result variable is showing on screen in that case temp is always empty conditionly if(temp=="" )//&& plus_slash_minus_flag==false) { String pm=""; pm=String.valueOf(result); if(result>0)
{
pm="-"+pm;
result=Double.parseDouble(pm);
lcdDisplay.setText(String.valueOf(result));
pm="";
}
else if(result<0)
{
pm=pm.substring(1,pm.length());
result=Double.parseDouble(pm);
lcdDisplay.setText(String.valueOf(result));
pm="";
}
System.out.println("result="+result);
}
}
//**********************************************************************************************
if(cmd=="%")
{
point_flag=true;
if(temp!="")
{
result=result/Double.parseDouble(temp);
result=result*100;
lcdDisplay.setText(String.valueOf(result));
}
//under construction
}
//**********************************************************************************************
//independcy
if(cmd=="1/x")
{
point_flag=true;
if(temp!="")
{
double byx=0;
byx=Double.parseDouble(temp);
byx=1/byx;
temp=String.valueOf(byx);
lcdDisplay.setText(temp);
}
if(temp=="")
{
result=1/result;
lcdDisplay.setText(String.valueOf(result));
}
//under construction
}
//**********************************************************************************************
//if(cmd=="+/-")
//{
//point_flag=true;
//}
//**********************************************************************************************
if(cmd=="MC")
{
point_flag=true;//must add to this flag coomaon in all operations must note that if any new operation added after
memory_flag=false;//means there is no value stored in M+
memory=0;
mem_recall.setEnabled(false);
mem_clear.setEnabled(false);
}
//**********************************************************************************************
if(cmd=="M+")
{
point_flag=true;
if(mr_flag==false)//used to specify that to store value from temp or result
if(temp!="")
{
memory_flag=true;
temp=lcdDisplay.getText();
memory=Double.parseDouble(temp);
mul_flag=false;
flag_minus_first=false;
divide_flag=false;
mem_recall.setEnabled(true);
mem_clear.setEnabled(true);
}
if(mr_flag==true)
{
System.out.println("ENTERED IN M+ where mr_flad=false");
memory_flag=true;
result=Double.parseDouble(lcdDisplay.getText());
memory=result;
mul_flag=false;
flag_minus_first=false;
divide_flag=false;
mr_flag=false;
mem_recall.setEnabled(true);
mem_clear.setEnabled(true);
}
}
//**********************************************************************************************
if(cmd=="MR")
{
point_flag=true;
if(memory_flag==true)//checks that if any number is stored using M+
{
temp=String.valueOf(memory);
lcdDisplay.setText(temp);
}
}
//**********************************************************************************************
if(cmd=="/")
{
point_flag=true;
if(sign=="-" && temp!="")
{
result=result-Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));
temp="";
divide_flag=false;
}
if(sign=="+" && temp!="")
{
result=Double.parseDouble(temp)+result;
lcdDisplay.setText(String.valueOf(result));
temp="";
divide_flag=false;
}
if(sign=="X" && temp!="")
{
result=result*Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));
temp="";
divide_flag=false;
}
sign="/";
if(temp!="")
{
if(divide_flag==true)
{
divide_temp=Double.parseDouble(temp)/divide_temp;
System.out.println("Divide_temp="+divide_temp);
lcdDisplay.setText(String.valueOf(divide_temp));
temp="";
divide_flag=false;
result=divide_temp;
System.out.println("result="+result);
}
if(divide_flag==false && temp!="")
{
result=result/Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));
System.out.println("result="+result);
temp="";
}
}
}
//**********************************************************************************************
if(cmd=="X")
{
point_flag=true;
if(sign=="/" && temp!="")
{
result=result/Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));
System.out.println("result="+result);
temp="";
mul_flag=false;
}
if(sign=="+" && temp!="")
{
result=Double.parseDouble(temp)+result;
lcdDisplay.setText(String.valueOf(result));
temp="";
mul_flag=false; //testing statement beta
}
if(sign=="-" && temp!="")
{
result=result-Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));
temp="";
mul_flag=false;///testing statement beta
}
sign="X";
if(temp!="")
{
if(mul_flag==true)
{
System.out.println("Entered in X where temp!=empty");
mul_temp=mul_temp*Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(mul_temp));
temp="";
result=mul_temp;
System.out.println("result="+result);
mul_flag=false;
}
else
{
System.out.println("Entered in cmd=X and where mul_flag=false");
result=result*Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));////////////////
temp="";
}
}
}
//**********************************************************************************************
if(cmd=="+")
{
point_flag=true;
if(sign=="/" && temp!="")
{
result=result/Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));
System.out.println("result="+result);
temp="";
}
if(sign=="X" && temp!="")
{
result=result*Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));
temp="";
}
if(sign=="-" && temp!="")//e.g 2-2+4 for this like operation
{
result=result-Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));
temp="";
}
sign="+";
if(temp!="")
{
mul_flag=false;
System.out.println(" Entered in + temp!=empty ");
result=Double.parseDouble(temp)+result;
lcdDisplay.setText(String.valueOf(result));
temp="";
System.out.println("result="+result);
System.out.println(String.valueOf(temp));
}
else
{
}
}
//**********************************************************************************************
if(cmd=="-")
{
point_flag=true;
if(sign=="/" && temp!="")
{
result=result/Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));
System.out.println("result="+result);
temp="";
flag_minus_first=false;
}
if(sign=="X" && temp!="")
{
result=result*Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));
temp="";
flag_minus_first=false;
}
if(sign=="+" && temp!="") //if user enters 2-2+anynumber
{
result=Double.parseDouble(temp)+result;
lcdDisplay.setText(String.valueOf(result));
temp="";
flag_minus_first=false;
}
sign="-";
if(temp!="")
{
mul_flag=false;
System.out.println(" Entered in - where temp!=empty ");
if(flag_minus_first==true)//when user first time perform -operation after starting pgm
{
result=Double.parseDouble(temp)-result;
flag_minus_first=false;
System.out.println(result);
}
else
{
result=result-Double.parseDouble(temp);
System.out.println(result);
}
lcdDisplay.setText(String.valueOf(result));
temp="";
}
}
//**********************************************************************************************
if(cmd=="=")
{
point_flag=true;
if(sign=="+")
if(temp!="")
{
mul_flag=false;
divide_flag=false;
flag_minus_first=false;//testing may be removed
result=Double.parseDouble(temp)+result;
lcdDisplay.setText(String.valueOf(result));
sign="";
temp="";
System.out.println("result="+result);
mr_flag=true;///used for memory recall mechanism
}
if(sign=="-")
if(temp!="")
{
mul_flag=false;
divide_flag=false;
flag_minus_first=false;//testing may be removed
result=result-Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));
sign="";
temp="";
System.out.println("result="+result);
mr_flag=true;///used for memory recall mechanism
}
if(sign=="X")
if(temp!="")
{
mul_flag=false;
divide_flag=false;
flag_minus_first=false;//testing may be removed
result=result*Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));
sign="";
temp="";
mr_flag=true;///used for memory recall mechanism
//mul_temp=1;
}
if(sign=="/")
if(temp!="")
{
mul_flag=false;
divide_flag=false;
flag_minus_first=false;//testing may be removed
result=result/Double.parseDouble(temp);
lcdDisplay.setText(String.valueOf(result));
sign="";
temp="";
mr_flag=true;///used for memory recall mechanism
}
if(sign=="")
if(temp!="")//testing may be removed
{
result=Double.parseDouble(lcdDisplay.getText());
System.out.println("result="+lcdDisplay.getText());
mul_flag=false;
mr_flag=true;///used for memory recall mechanism
}
temp="";
}
//**********************************************************************************************
if(cmd=="."||cmd=="0" || cmd=="1" || cmd=="2" || cmd=="3" || cmd=="4" || cmd=="5" || cmd=="6" || cmd=="7" || cmd=="8" || cmd=="9")
{
if(cmd=="." && temp=="" && point_flag==true)
{
temp="0";
temp=temp+cmd;
point_flag=false;
}
else if(cmd=="." && temp!="" && point_flag==true)
{
temp=temp+cmd;
point_flag=false;
}
//temp=temp+cmd;
else if(cmd!=".")
temp=temp+cmd;
lcdDisplay.setText(temp);
System.out.println("temp"+temp);
mr_flag=false;
}
//**********************************************************************************************
if(cmd=="C")
{
//plus_slash_minus_flag=true;
point_flag=true;
mr_flag=false;
divide_temp=1;
divide_flag=true;
mul_flag=true;
temp="";
lcdDisplay.setText("0");
result=0;
sign="";
flag_minus_first=true;
mul_temp=1;
System.out.println("result="+result);
System.out.println("temp="+temp);
}
//**********************************************************************************************
}
}
}
Calculator
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
*/
public class Calculator extends Applet implements ActionListener
{
Button CE;
Button Dot=new Button(".");
Button Add=new Button(" + ");
Button Sub=new Button(" - ");
Button Mul=new Button(" * ");
Button Div=new Button(" / ");
Button Eql=new Button(" = ");
Button Sqrt=new Button("v");
TextField DataInput;
boolean Clear=false;
boolean Result=false;
String Num="";
String IP1="";
String IP2="";
String Res="";
String Op="";
Double Oper1;
Double Oper2;
Double ResInt;
public void init()
{
DataInput=new TextField(20);
Button But0=new Button(" 0 ");
Button But1=new Button(" 1 ");
Button But2=new Button(" 2 ");
Button But3=new Button(" 3 ");
Button But4=new Button(" 4 ");
Button But5=new Button(" 5 ");
Button But6=new Button(" 6 ");
Button But7=new Button(" 7 ");
Button But8=new Button(" 8 ");
Button But9=new Button(" 9 ");
CE=new Button(" CE ");
But0.addActionListener(this);
But1.addActionListener(this);
But2.addActionListener(this);
But3.addActionListener(this);
But4.addActionListener(this);
But5.addActionListener(this);
But6.addActionListener(this);
But7.addActionListener(this);
But8.addActionListener(this);
But9.addActionListener(this);
Dot.addActionListener(this);
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
Eql.addActionListener(this);
CE.addActionListener(this);
Sqrt.addActionListener(this);
add(DataInput);
add(But0);
add(But1);
add(But2);
add(But3);
add(But4);
add(But5);
add(But6);
add(But7);
add(But8);
add(But9);
add(Dot);
add(Add);
add(Sub);
add(Mul);
add(Div);
add(Eql);
add(CE);
add(Sqrt);
setLayout(null);
DataInput.setBounds(20,20,260,20);
But0.setBounds(20,50,30,30);
But1.setBounds(60,50,30,30);
But2.setBounds(100,50,30,30);
But3.setBounds(140,50,30,30);
But4.setBounds(180,50,30,30);
But5.setBounds(20,100,30,30);
But6.setBounds(60,100,30,30);
But7.setBounds(100,100,30,30);
But8.setBounds(140,100,30,30);
But9.setBounds(180,100,30,30);
Dot.setBounds(70,150,70,30);
Add.setBounds(230,50,50,30);
Sub.setBounds(230,100,50,30);
Mul.setBounds(230,150,50,30);
Div.setBounds(280,100,50,30);
Eql.setBounds(280,150,50,30);
CE.setBounds(280,50,50,30);
Sqrt.setBounds(150,150,70,30);
}
public void paint(Graphics Grp)
{
setBackground(Color.gray);
CE.setForeground(Color.blue);
Add.setForeground(Color.red);
Sub.setForeground(Color.red);
Mul.setForeground(Color.red);
Div.setForeground(Color.red);
Eql.setForeground(Color.red);
Dot.setForeground(Color.blue);
if(Clear==true)
{
DataInput.setText("");
Clear=false;
if(Result==true)
{
DataInput.setText(Res);
Result=false;
}
}
else
DataInput.setText(DataInput.getText()+Num);
}
public void actionPerformed(ActionEvent Ae)
{
if(Ae.getActionCommand().equals(" 0 "))
{
Num="0";
repaint();
}
if(Ae.getActionCommand().equals(" 1 "))
{
Num="1";
repaint();
}
if(Ae.getActionCommand().equals(" 2 "))
{
Num="2";
repaint();
}
if(Ae.getActionCommand().equals(" 3 "))
{
Num="3";
repaint();
}
if(Ae.getActionCommand().equals(" 4 "))
{
Num="4";
repaint();
}
if(Ae.getActionCommand().equals(" 5 "))
{
Num="5";
repaint();
}
if(Ae.getActionCommand().equals(" 6 "))
{
Num="6";
repaint();
}
if(Ae.getActionCommand().equals(" 7 "))
{
Num="7";
repaint();
}
if(Ae.getActionCommand().equals(" 8 "))
{
Num="8";
repaint();
}
if(Ae.getActionCommand().equals(" 9 "))
{
Num="9";
repaint();
}
if(Ae.getActionCommand().equals("."))
{
Num=".";
repaint();
}
if(Ae.getActionCommand().equals(" CE "))
{
Clear=true;
IP1="";
IP2="";
Res="";
repaint();
}
if(Ae.getActionCommand().equals(" + "))
{
IP1=DataInput.getText();
Op="+";
Clear=true;
repaint();
}
if(Ae.getActionCommand().equals(" - "))
{
IP1=DataInput.getText();
Op="-";
Clear=true;
repaint();
}
if(Ae.getActionCommand().equals(" * "))
{
IP1=DataInput.getText();
Op="*";
Clear=true;
repaint();
}
if(Ae.getActionCommand().equals(" / "))
{
IP1=DataInput.getText();
Op="/";
Clear=true;
repaint();
}
if(Ae.getActionCommand().equals("v"))
{
IP1=DataInput.getText();
Op="v";
Clear=true;
repaint();
}
if(Ae.getActionCommand().equals(" = "))
{
IP2=DataInput.getText();
double I1,I2;
double ROut=0;
I1=Oper1.parseDouble(IP1);
I2=Oper2.parseDouble(IP2);
if(Op=="+")
ROut=I1+I2;
if(Op=="-")
ROut=I1-I2;
if(Op=="*")
ROut=I1*I2;
if(Op=="/")
ROut=I1/I2;
ResInt=new Double(ROut);
Res=ResInt.toString();
IP1=IP2;
Result=true;
Clear=true;
repaint();
}
else if(Ae.getActionCommand().equals("v"))
{
double I1;
double ROut=0;
I1=Oper1.parseDouble(IP1);
if(Op=="v")
ROut=Math.sqrt(I1);
ResInt=new Double(ROut);
Res=ResInt.toString();
IP1=IP2;
Result=true;
Clear=true;
repaint();
}
}
}
DESIGNING OF PAINT BRUSH USING JAVA
import java.awt.*;
import java.awt.event.*;
/* */
class brush extends Frame
{
String mg=" ";
CheckboxMenuItem red,blue;
brush(String title)
{
super(title);
MenuBar mbar=new MenuBar();
setMenuBar(mbar);
Menu draw=new Menu("DRAW");
MenuItem d1,d2,d3,d4,d5,d6;
draw.add(d1=new MenuItem("LINE"));
draw.add(d2=new MenuItem("CIRCLE"));
draw.add(d3=new MenuItem("SQUARE"));
draw.add(d4=new MenuItem("-"));
Menu sub=new Menu("Fill",true);
MenuItem s1,s2,s3;
sub.add(s1=new MenuItem("Circle"));
sub.add(s2=new MenuItem("Square"));
draw.add(sub);
draw.add(d5=new MenuItem("-"));
draw.add(d6=new MenuItem("Close"));
mbar.add(draw);
Menu col=new Menu("Color");
col.add(red=new CheckboxMenuItem("red"));
col.add(blue=new CheckboxMenuItem("Blue"));
mbar.add(col);
MenuHandler handle=new MenuHandler(this);
d1.addActionListener(handle);
d2.addActionListener(handle);
d3.addActionListener(handle);
d4.addActionListener(handle);
d6.addActionListener(handle);
s1.addActionListener(handle);
s2.addActionListener(handle);
red.addItemListener(handle);
blue.addItemListener(handle);
blue.setState(true);
Myadapter ad=new Myadapter(this);
addWindowListener(ad);
}
public void paint(Graphics g)
{
if(red.getState())
{
g.setColor(Color.red);
blue.setState(false);
}
else if(blue.getState())
{
g.setColor(Color.blue);
red.setState(false);
}
else
{
red.setState(false);
blue.setState(false);
g.setColor(Color.black);
}
if(mg=="circle")
g.drawOval(150,150,200,200);
else if(mg=="line")
g.drawLine(0,0,200,200);
else if(mg=="square")
{
g.drawRect(100,100,200,200);
}
else if(mg=="fillc")
g.fillOval(150,150,200,200);
else if(mg=="fills")
g.fillRect(100,100,200,200);
if(mg=="close")
setVisible(false);
}
}
class Myadapter extends WindowAdapter
{
brush br;
public Myadapter(brush bru)
{
this.br=bru;
}
public void WindowClosing(WindowEvent we)
{
br.setVisible(false);
}
}
class MenuHandler implements ActionListener,ItemListener
{
brush br;
public MenuHandler(brush bru)
{
this.br=bru;
}
public void actionPerformed(ActionEvent ae)
{
String arg=ae.getActionCommand();
if(arg.equals("LINE"))
br.mg="line";
else if(arg.equals("CIRCLE"))
br.mg="circle";
else if(arg.equals("SQUARE"))
br.mg="square";
else if(arg.equals("Circle"))
br.mg="fillc";
else if(arg.equals("Square"))
br.mg="fills";
br.repaint();
}
public void itemStateChanged(ItemEvent ie)
{ }
}
public class paintbrush extends Applet
{
Frame f;
public void init()
{
f=new brush("Paint Brush Application");
f.setSize(300,400);
f.setVisible(true);
}
public void start()
{
f.setVisible(true);
}
public void stop()
{
f.setVisible(false);
}
}
File Transfer Protocol using Java
import java.io.*;
import java.net.*;
class FTPserver
{
public static void main(String[] args)
{
ServerSocket server;
Socket s;
BufferedReader fromsoc,fromfile;
PrintStream tosoc;
String line;
FileInputStream fis;
try
{
server=new ServerSocket(6020);
System.out.println("server waiting");
s=server.accept();
System.out.println("connected");
fromsoc=new BufferedReader(new InputStreamReader(s.getInputStream()));
line=fromsoc.readLine();
fis=new FileInputStream(line);
fromfile=new BufferedReader(new InputStreamReader(fis));
tosoc=new PrintStream(s.getOutputStream());
while((line=fromfile.readLine())!=null)
{
tosoc.println(line);
System.out.println(line);
} tosoc.println("exit");
server.close();
s.close();
fis.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
CLIENT :
import java.io.*;
import java.net.*;
class FTPclient
{
public static void main(String[] args)
{
Socket s;
BufferedReader fromsoc,fromuser;
PrintStream tosoc,toFile;
String line;
FileOutputStream fos;
try
{
s=new Socket(InetAddress.getByName("localhost"),6020);
System.out.println("enter filename:\n");
fromuser=new BufferedReader(new InputStreamReader(System.in));
line=fromuser.readLine();
tosoc=new PrintStream(s.getOutputStream());
tosoc.println(line);
fromsoc=new BufferedReader(new InputStreamReader(s.getInputStream()));
fos=new FileOutputStream("new.txt");
toFile=new PrintStream(fos);
while(!(line=fromsoc.readLine()).equals("exit"))
{
toFile.println(line);
System.out.println(line);
}
s.close();
fos.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Send Email
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailSender {
public static void main(String ar[]) throws Exception{
String smtpHost = "smtp.mail.yahoo.com",
user = "aaa@aa.com",
password = "1234",
to ="csnair1981@yahoo.com",
subject="hi how r u ",
fromName = "abcd@gmail.com";
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", "http");
props.put("mail.pop.port", 587);
// Authenticator auth = new PopupAuthenticator ();
Session session = Session.getInstance(props);
// Address replyToList[] = { new InternetAddress("csnair1981@yahoo.com") };
Address toList[] = { new InternetAddress("csnair1981@yahoo.com") };
Message newMessage = new MimeMessage(session);
newMessage.setFrom(new InternetAddress(fromName));
// newMessage.setReplyTo(replyToList);
newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
newMessage.setSubject(subject);
newMessage.setText("This is is a test mail from java ");
// newMessage.setSentDate(sentDate);
Transport transport = session.getTransport("smtp");
transport.connect(smtpHost, user, password);
transport.sendMessage(newMessage, toList);
}
}
Thursday, December 3, 2009
Program to develop a Mail Client in Java.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class MailClient
{
public static void main(String []args)
{
JFrame frame = new MailClientFrame();
frame.show();
}
}
class MailClientFrame extends JFrame implements ActionListener
{
private BufferedReader in;
private PrintWriter out;
private JTextField from;
private JTextField to;
private JTextField smtpServer;
private JTextArea message;
private JTextArea response;
private JLabel fromLbl;
private JLabel toLbl;
private JLabel serverLbl;
public MailClientFrame()
{
setTitle("Mail Client");
setSize(250,400);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
fromLbl = new JLabel("From: ");
getContentPane().add(fromLbl);
from = new JTextField(20);
getContentPane().add(from);
toLbl = new JLabel("To: ");
getContentPane().add(toLbl);
to = new JTextField(20);
getContentPane().add(to);
serverLbl = new JLabel("SMTP Server:");
getContentPane().add(serverLbl);
smtpServer = new JTextField(20);
getContentPane().add(smtpServer);
message = new JTextArea(5,20);
getContentPane().add(message);
JScrollPane p = new JScrollPane(message);
getContentPane().add(p);
response = new JTextArea(5,20);
getContentPane().add(response);
JScrollPane p1 = new JScrollPane(response);
getContentPane().add(p1);
JButton sendButton = new JButton("Send");
sendButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(sendButton);
getContentPane().add(sendButton);
}
public void actionPerformed(ActionEvent evt)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
sendMail();
}
}
);
}
public void sendMail()
{
try
{
Socket s = new Socket(smtpServer.getText(),25);
out = new PrintWriter(s.getOutputStream());
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String hostName = InetAddress.getLocalHost().getHostName();
send(null);
send("HELO" + hostName);
send("MAIL FROM:"+ from.getText());
send("RCPT TO:" + to.getText());
send("DATA");
out.println(message.getText());
send(".");
s.close();
}
catch(IOException e)
{
response.append("Error:" + e);
}
}
public void send(String s) throws IOException
{
if(s!=null)
{
response.append(s+"
");
out.println(s);
out.flush();
}
String line;
if ( (line = in.readLine())!=null)
{
response.append(line+"
");
}
}
}
A Simple Client-Server Multicasting
Code :
/*
Client Setting
NetConference.
______________
*/
/* Tips to run this :
__________________
(After compiling chatkaro12mserver.java)
Step1: Open another prompt and run java chatkaro12mclient 127.0.0.1.
___________________________________
*/
/*
Server Setting
** NetConference**
__________________
*/
/* Tips to run this:
__________________
Step1: Open command prompt and run java chatkaro12mserver.
______________________
Step2: Continue with client program.
*/
//Code: chatkaro12mserver.java
// Program Starts...
import java.io.*;
import java.net.*;
import java.util.Vector;
import java.util.Enumeration;
public class chatkaro12mServer
{
//static String k=socket.getInetAddress().getHostName();
private int port=5001;
private boolean li=true;
private Vector clients=new Vector();
public static void main(String a[])
{
System.out.println(" Press ctrl-c to Quit.");
new chatkaro12mServer().server();
}
void server()
{
ServerSocket serverSock=null;
try
{
InetAddress serverAddr=InetAddress.getByName(null);
System.out.println("Waiting for"+serverAddr.getHostName()+"on
port"+port);
serverSock=new ServerSocket(port,50);
}
catch(IOException e)
{
System.out.println(e.getMessage()+":Failed");
return;
}
while(li)
{
try
{
Socket socket=serverSock.accept();
System.out.println("Accept
"+socket.getInetAddress().getHostName());
DataOutputStream remoteOut= new
DataOutputStream(socket.getOutputStream());
clients.addElement(remoteOut);
new ServerHelper(socket,remoteOut,this).start();
}
catch(IOException e)
{
System.out.println(e.getMessage()+":Failed");
}
}
if(serverSock !=null)
{
try
{
serverSock.close();
}
catch(IOException x)
{
}
}
}
synchronized Vector getClients()
{
return clients;
}
synchronized void removeFromClients(DataOutputStream remoteOut)
{
clients.removeElement(remoteOut);
}
}
class ServerHelper extends Thread
{
private Socket sock;
private DataOutputStream remoteOut;
private chatkaro12mServer server;
private boolean li=true;
private DataInputStream remoteIn;
ServerHelper(Socket sock,DataOutputStream remoteOut,chatkaro12mServer
server) throws IOException
{
this.sock=sock;
this.remoteOut=remoteOut;
this.server=server;
remoteIn=new DataInputStream(sock.getInputStream());
}
public synchronized void run()
{
String s;
try
{
while(li)
{
s=remoteIn.readUTF();
broadcast(s);
}
}
catch(IOException e)
{
System.out.println(e.getMessage()+"connection lost");
}
finally
{
try
{
cleanUp();
}
catch (IOException x)
{
}
}
}
private void broadcast(String s)
{
Vector clients=server.getClients();
DataOutputStream dataOut=null;
for(Enumeration e=clients.elements();
e.hasMoreElements(); )
{
dataOut=(DataOutputStream)(e.nextElement());
if(!dataOut.equals(remoteOut))
{
try
{
dataOut.writeUTF(s);
}
catch(IOException x)
{
System.out.println(x.getMessage()+"Failed");
server.removeFromClients(dataOut);
}
}
}
}
private void cleanUp() throws IOException
{
if(remoteOut!=null)
{
server.removeFromClients(remoteOut);
remoteOut.close();
remoteOut=null;
}
if(remoteIn!=null)
{
remoteIn.close();
remoteIn=null;
}
if(sock!=null)
{
sock.close();
sock=null;
}
}
protected void finalize() throws Throwable
{
try
{
cleanUp();
}
catch(IOException x)
{
}
super.finalize();
}
}
Code: chatkaro12mclient.java
// Program Starts...
import java.io.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class chatkaro12mClient extends Panel
{
TextArea receivedText;
Socket sock;
private GridBagConstraints c;
private GridBagLayout gridBag;
private Frame frame;
private Label label;
JButton send;
JButton exit;
private int port=5001;
private TextArea sendText;
private String hostname;
private String username;
private DataOutputStream remoteOut;
ImageIcon i1,i2;
public static void main(String args[])
{
if(args.length != 2)
{
System.out.println("Format is : java chatkaro12mClient ");
return;
}
Frame f1=new Frame("Welcome Protocol");
f1.resize(800,600);
f1.show();
JOptionPane.showMessageDialog(f1,"Welcome "+args[0]+".. Have a nice
Session.","Welcome",0);
Frame f= new Frame("Connecting to Mr. "+args[0]);
chatkaro12mClient chat=new chatkaro12mClient(f,args[0],args[1]);
f.add("Center",chat);
f.setSize(800,600);
f.show();
chat.client();
}
public chatkaro12mClient(Frame f,String user,String host)
{
frame=f;
frame.addWindowListener(new WindowExitHandler());
username=user;
hostname=host;
//Insets insets=new Insets(10,20,5,10);
//gridBag=new GridBagLayout();
//setLayout(gridBag);
/*c=new GridBagConstraints();
c.insets=insets;
c.gridy=0;
c.gridx=0;*/
label=new Label("Text to send :");
add(label);
/*gridBag.setConstraints(label,c);
c.gridx=1;*/
sendText=new TextArea(15,30);
/*sendText.addActionListener(new TextActionHandler());
gridBag.setConstraints(sendText,c);*/
add(sendText);
//c.gridy=1;
//c.gridx=0;
label= new Label("Text received :");
//gridBag.setConstraints(label,c);
add(label);
//c.gridx=1;
receivedText=new TextArea(15,30);
//gridBag.setConstraints(receivedText,c);
add(receivedText);
ImageIcon i1=new ImageIcon("click.gif");
ImageIcon i2=new ImageIcon("doorin2.gif");
send=new JButton(i1);
exit=new JButton(i2);
add(send);
add(exit);
send.addActionListener(new TextActionHandler());
exit.addActionListener(new EXIT());
}
void client()
{
try
{
if(hostname.equals("local"))
hostname=null;
InetAddress serverAddr= InetAddress.getByName(hostname);
sock=new Socket(serverAddr.getHostName(),port);
remoteOut=new DataOutputStream(sock.getOutputStream());
System.out.println("Connected to server " + serverAddr.getHostName() +
"
on port " + sock.getPort());
new chatkaro12mClientReceive(this).start();
}
catch(IOException e)
{
System.out.println(e.getMessage() + " : Failed to connect to
server.");
}
}
protected void finalize() throws Throwable
{
try
{
if(remoteOut != null)
remoteOut.close();
if(sock != null)
sock.close();
}
catch(IOException x)
{}
super.finalize();
}
class WindowExitHandler extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
Window w=e.getWindow();
w.setVisible(false);
w.dispose();
System.exit(0);
}
}
class EXIT implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if((JOptionPane.showConfirmDialog(new Frame(),"Are You Sure to close
the Session?"))==JOptionPane.YES_OPTION)
{
JOptionPane.showMessageDialog(new Frame(),"Thank U. Visit Again.
","Good Bye",0);
System.exit(0);
}
}
}
class TextActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try
{
remoteOut.writeUTF(sendText.getText());
JOptionPane.showMessageDialog(new Frame(),"Your msg has been sent
","Confirmation",0);
sendText.setText("");
}
catch(IOException x)
{
System.out.println(x.getMessage() + " : connection to peer lost.");
}
}
}
}
class chatkaro12mClientReceive extends Thread
{
private chatkaro12mClient chat;
chatkaro12mClientReceive(chatkaro12mClient chat)
{
this.chat=chat;
}
public synchronized void run()
{
String s;
DataInputStream remoteIn=null;
try
{
remoteIn= new DataInputStream(chat.sock.getInputStream());
while(true)
{
s=remoteIn.readUTF();
chat.receivedText.setText(s);
}
}
catch(IOException e)
{
System.out.println(e.getMessage() + " : connection to peer lost.");
}
finally
{
try
{
if(remoteIn !=null)
remoteIn.close();
}
catch(IOException x)
{}
}
}
}
FTP Server and FTP Client (Complete Project)
//FtpServer.java
import java.io.*;
import java.net.*;
public class FtpServer
{
public static void main(String [] args)
{
int i=1;
System.out.println("******************************************************
**************************");
System.out.println("****************************** FTP
SERVER
***********************************");
System.out.println("******************************************************
**************************");
System.out.println("Server Started...");
System.out.println("Waiting for connections...");
System.out.println("
");
try
{
ServerSocket s = new ServerSocket(100);
for(;;)
{
Socket incoming = s.accept();
System.out.println("New Client Connected with id "
+ i
+" from "+incoming.getInetAddress().getHostName()+"..." );
Thread t = new ThreadedServer(incoming,i);
i++;
t.start();
}
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
}
class ThreadedServer extends Thread
{
int n;
String c,fn,fc;
String filenm;
Socket incoming;
int counter;
String dirn="c:/FTP SERVER DIRECTORY";
public ThreadedServer(Socket i,int c)
{
incoming=i;
counter=c;
}
public void run()
{
try
{
BufferedReader in =new BufferedReader(new
InputStreamReader(incoming.getInputStream()));
PrintWriter out = new
PrintWriter(incoming.getOutputStream(), true);
OutputStream output=incoming.getOutputStream();
fn=in.readLine();
c=fn.substring(0,1);
if(c.equals("#"))
{
n=fn.lastIndexOf("#");
filenm=fn.substring(1,n);
FileInputStream fis=null;
boolean filexists=true;
System.out.println("Request to download file "+filenm+"
recieved from "+incoming.getInetAddress().getHostName()+"...");
try
{
fis=new FileInputStream(filenm);
}
catch(FileNotFoundException exc)
{
filexists=false;
System.out.println("FileNotFoundException:
"+exc.getMessage());
}
if(filexists)
{
sendBytes(fis, output) ;
fis.close();
}
}
else
{
try
{
boolean done=true;
System.out.println("Request to upload file " +fn+"
recieved from "+incoming.getInetAddress().getHostName()+"...");
File dir=new File(dirn);
if(!dir.exists())
{
dir.mkdir();
}
else
{}
File f=new File(dir,fn);
FileOutputStream fos=new FileOutputStream(f);
DataOutputStream dops=new DataOutputStream(fos);
while(done)
{
fc=in.readLine();
if(fc==null)
{
done=false;
}
else
{
dops.writeChars(fc);
// System.out.println(fc);
}
}
fos.close();
}
catch(Exception ecc)
{
System.out.println(ecc.getMessage());
}
}
incoming.close();
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
private static void sendBytes(FileInputStream f,OutputStream op)
throws Exception
{
byte[] buffer=new byte[1024];
int bytes=0;
while((bytes=f.read(buffer))!=-1)
{
op.write(buffer,0,bytes);
}
}
}
//FtpClient.java
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
class FtpClient extends JFrame implements ActionListener
{
String fn,filenm;
String fc;
String dirn="c:/FTP CLIENT DIRECTORY";
JPanel pnl;
JLabel lbltle,lblud;
Font fnt;
JTextField txtfn;
JButton btnu,btnd;
Socket s;
InputStreamReader in;
OutputStream out;
BufferedReader br;
PrintWriter pw;
public FtpClient()
{
super("FTP CLIENT");
pnl=new JPanel(null);
fnt=new Font("Times New Roman",Font.BOLD,25);
lbltle=new JLabel("FTP CLIENT");
lbltle.setFont(fnt);
lbltle.setBounds(225,35,200,30);
pnl.add(lbltle);
lblud=new JLabel("ENTER FILE-NAME :");
lblud.setBounds(100,100,150,35);
pnl.add(lblud);
txtfn=new JTextField();
txtfn.setBounds(300,100,200,25);
pnl.add(txtfn);
btnu=new JButton("UPLOAD");
btnu.setBounds(150,200,120,35);
pnl.add(btnu);
btnd=new JButton("DOWNLOAD");
btnd.setBounds(320,200,120,35);
pnl.add(btnd);
btnu.addActionListener(this);
btnd.addActionListener(this);
getContentPane().add(pnl);
try
{
s=new Socket("localhost",100);
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
pw=new PrintWriter(s.getOutputStream(),true);
out=s.getOutputStream();
}
catch(Exception e)
{
System.out.println("ExCEPTION :"+e.getMessage());
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btnu)
{
try
{
filenm=txtfn.getText();
pw.println(filenm);
FileInputStream fis=new FileInputStream(filenm);
byte[] buffer=new byte[1024];
int bytes=0;
while((bytes=fis.read(buffer))!=-1)
{
out.write(buffer,0,bytes);
}
fis.close();
}
catch(Exception exx)
{
System.out.println(exx.getMessage());
}
}
if(e.getSource()==btnd)
{
try
{
File dir=new File(dirn);
if(!dir.exists())
{
dir.mkdir();
}
else{}
boolean done=true;
filenm=txtfn.getText();
fn=new String("#"+filenm+"#");
//System.out.println(filenm);
pw.println(fn);
File f=new File(dir,filenm);
FileOutputStream fos=new FileOutputStream(f);
DataOutputStream dops=new DataOutputStream(fos);
while(done)
{
fc=br.readLine();
if(fc==null)
{
done=false;
}
else
{
dops.writeChars(fc);
// System.out.println(fc);
}
}
fos.close();
}
catch(Exception exx)
{}
}
}
public static void main(String args[])
{
FtpClient ftpc=new FtpClient();
ftpc.setSize(600,300);
ftpc.show();
}
}
Rapid Roll game
import java.awt.*; //CHANGE THE scrollSpeed value
if
it
import java.awt.event.*; //to run the thread with more
speed
import java.util.*;
import java.io.*;
class HighSc
{
int hsc;
BufferedReader br;
FileInputStream fis;
String sths;
public String getHighScore() throws IOException
{
fis = new FileInputStream("highscore.txt");
br = new BufferedReader(new InputStreamReader(fis));
sths = br.readLine();
fis.close();
return sths;
}
}
class GameFrame extends Frame implements Runnable, KeyListener
,ActionListener
{
MenuBar mb;
Menu m1;
MenuItem mi1,mi2,mi3,mi4,mi5,mi6;
Button b1,b2,b3;
Button ball;
Button oneUp;
final int TOPLINE = 50;
final int BOTTOMLINE = 350;
final int LEFTLINE = 20;
final int RIGHTLINE = 350 ;
int scrollSpeed = 25;
int x=50, y=300;
int x2=125,y2=200;
int x3 = 90,y3=100;
int bx = 80;
int by = 239;
int ox = 0;
int oy = 0;
int score = 0;
int oneUpCount = 1;
int t1,t2,t3;
int chances=3;
int a,b,c;
int diff = 65;
String msg = "";
String chns = "";
String st = "";
char ch;
int kcode;
boolean flagLKey = true;
boolean flagRKey = true;
boolean flagTop1 = false;
boolean flagTop2 = false;
boolean flagTop3 = false;
boolean flagDrop = true;
boolean flagMove = true;
boolean flagBetween = true;
boolean flagOnx = true;
boolean flagOnx2 = false;
boolean flagOnx3 = false;
boolean flagJump = true;
boolean flagNew1 = false;
boolean flagOneUp = false;
Thread t;
GameFrame()
{
mb = new MenuBar();
m1 = new Menu("File");
mi1 = new MenuItem("New Game");
mi2 = new MenuItem("HighScores");
mi3 = new MenuItem("Exit");
setMenuBar(mb);
mb.add(m1);
m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
setTitle("simple frame");
setSize(400,350);
setLayout(null);
b1 = new Button("");
b2 = new Button("");
b3 = new Button("");
ball = new Button("o");
oneUp = new Button("0");
add(ball);
add(b1);
add(b2);
add(b3);
add(oneUp);
b1.setBounds(x,y,70,20);
b2.setBounds(x2,y2,70,20);
b3.setBounds(x3,y3,70,20);
ball.setBounds(bx,by,10,10);
oneUp.setBounds(bx-5,by,5,5);
setBackground(Color.blue);
setForeground(Color.white);
ball.addKeyListener(this);
mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
closeAll();
}
});
t = new Thread(this,"game");
t.start();
} //end of constructor
public void actionPerformed(ActionEvent ae)
{
st = ae.getActionCommand();
if(st.equals("New Game"))
{
stop();this.setVisible(false);
Frame ng = new GameFrame();
ng.setVisible(true);
}
else if(st.equals("HighScores"))
{
HighSc hs = new HighSc();
try
{
msg = "";
msg = hs.getHighScore(); repaint();
}
catch(IOException ie)
{
System.out.println(ie);
}
}
else if(st.equals("Exit"))
{
closeAll();
}
}
public void closeAll()
{
stop();
t = null;
System.exit(0);
}
public void keyPressed(KeyEvent ke)
{
kcode = ke.getKeyCode();
switch(kcode)
{
case KeyEvent.VK_LEFT:
if(flagDrop)
bx -= 4;
if(ox<=bx+2&&ox>=bx&&(oy>=by&&oy<=by+6))
{
chances++;ox = 0;oy = 0;
repaint(); flagOneUp = false;
}
while(flagLKey)
{
if(((bx>=x&&bx<=x+70)&&(by
||((bx>=x2&&bx<=x2+70)&&(by
||((bx>=x3&&bx<=x3+70)&&(by
{
flagBetween = true;
bx -= 2; flagDrop = false;
}
else
{
flagDrop = true;
flagBetween = false;
if(flagOnx)
flagOnx = false;
else if(flagOnx2)
flagOnx2 = false;
else if(flagOnx3)
flagOnx3 = false;
break;
}
repaint(); break;
}
break;
case KeyEvent.VK_RIGHT:
if(flagDrop)
bx +=4;
if(ox<=bx+2&&ox>=bx&&(oy>=by&&oy<=by+6))
{
chances++; ox = 0; oy = 0;
repaint(); flagOneUp = false;
}
while(flagRKey)
{
if(((bx>=x&&bx<=x+70)&&(by
||((bx>=x2&&bx<=x2+70)&&(by
||((bx>=x3&&bx<=x3+70)&&(by
{
bx += 2;
flagBetween = true;
flagDrop = false;
repaint(); break;
}
else
{
flagBetween = false;
flagDrop = true;
if(flagOnx)
flagOnx = false;
else if(flagOnx2)
flagOnx2 = false;
else if(flagOnx3)
flagOnx3 = false;
break;
}
}
break;
}
}
public void keyReleased(KeyEvent ke)
{
if(bx
flagLKey = false;
flagRKey = true;
}
else if(bx>BOTTOMLINE)
{
flagRKey = false;
flagLKey = true;
}
else
{
flagLKey = true;
flagRKey = true;
}
}
public void keyTyped(KeyEvent ke)
{
}
public void flagDropFun()
{
while(flagDrop)
{
by += 1;
if(((bx>=x&&bx<=x+70)&&(by
||((bx>=x2&&bx<=x2+70)&&(by
||((bx>=x3&&bx<=x3+70)&&(by
{
flagDrop = false;
flagBetween = true;
if(!flagOnx2&&!flagOnx3&&(bx>=x&&bx<=x+70)&&(by
{
flagOnx = true; flagJump = true;score +=5;
flagOnx2 = false;
flagOnx3 = false;
}
else
if(!flagOnx&&!flagOnx3&&(bx>=x2&&bx<=x2+70)&&(by
{
flagOnx2 = true; flagJump = true; score += 5;
flagOnx = false;
flagOnx3 = false;
}
else
if(!flagOnx&&!flagOnx2&&(bx>=x3&&bx<=x3+70)&&(by
{
flagOnx3 = true; flagJump = true; score +=5;
flagOnx = false;
flagOnx2 = false;
}
else
{
flagOnx = false;
flagOnx2 = false;
flagOnx3 = false;
}
}
repaint(); break;
}
}
public void run()
{
try
{
while(flagMove)
{
while(flagDrop)
{
flagDropFun();break;
}
a = (int)(Math.random()*100);
b = (int)(Math.random()*100);
c = (int)(Math.random()*10);
if(y
oneUpCount++;
if(oy
ox=0; oy =0; flagOneUp = false;
}
}
if(y
x = a+b+c;
y = y2+100;
if(by
bx = x+30;
by = y-11;
flagNew1 = false;
flagOnx = true;
flagBetween = true;
}
}
else if(y2
x2 = a+b+c;
y2 = y3+100;
if(by<39||flagNew1)
{
bx = x2+30;
by = y2-11;
flagNew1 = false;
flagOnx2 = true;
flagBetween = true;
}
}
else if(y3
x3 = a+b+c;
y3 = y+100;
if(by<39||flagNew1)
{
bx = x3+30;
by = y3-11;
flagOnx3 = true;
flagNew1 = false;
flagOnx3 = true;
flagBetween = true;
}
}
y -= 1;
y2 -=1;
y3 -= 1;
if(flagOneUp)
{
if(t2==1)
{
ox = x+t2+t3;
oy = y-5;
}
else if(t2==2)
{
ox = x2+t2+t3;
oy = y2-5;
}
else if(t2==3)
{
ox = x3+t2+t3;
oy = y3-5;
}
}
if(oneUpCount==7)
{
t1 =(int)(Math.random()*10);
t3 = (int)(Math.random()*10);
t2 = (int)(t1/3)+1;
flagOneUp = true;
oneUpCount = 1;
}
if(by
if(by
t.sleep(100);
chances--;
}
if(chances==0)
{
msg = "Game Over"; repaint();
stop();
}
}
if((flagOnx&&flagBetween))
{
if(!flagLKey&&!flagRKey)
{
bx = x+30;
}
by = y-11;
flagJump = false;
}
else if((flagOnx2&&flagBetween))
{
if(!flagLKey&&!flagRKey)
bx = x2+30;
by = y2-11;
flagJump = false;
}
else if(flagOnx3&&flagBetween)
{
if(!flagLKey&&!flagRKey)
bx = x3+30;
by = y3-11;
flagJump = false;
}
while(flagDrop)
{
by += 1;
if(by>BOTTOMLINE)
{
chances--;
flagNew1 = true;
flagDrop = false;
t.sleep(100);
if(chances == 0)
{
msg = "Game Over"; repaint();
stop();
}
}
repaint(); break;
}
/* if(score%50==0)
{
scrollSpeed -= 3; score += 5;
} */
repaint();
Thread.sleep(scrollSpeed);
} //end of while flagMove
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
}
public void stop()
{
flagMove = false;
t = null;
}
public void paint(Graphics g)
{
b1.setBounds(x,y,70,20);
b2.setBounds(x2,y2,70,20);
b3.setBounds(x3,y3,70,20);
ball.setBounds(bx,by,10,10);
oneUp.setBounds(ox,oy,5,5);
g.drawString("Score :"+score,280,65);
g.drawString("Chances :"+chances,280,75);
g.drawString(msg,100,100);
}
} // end of BFrame
public class RapidRollGame
{
public static void main(String []args)
{
Frame f1 = new GameFrame();
f1.setVisible(true);
}
}
Sending mail Using JavaMail to Yahoo and Gmail accounts
import java.io.File;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class GoogleTest {
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final String SMTP_PORT = "465";
private static final String emailMsgTxt = "Test Message Contents";
private static final String emailSubjectTxt = "A test from gmail";
private static final String emailFromAddress = "xxx@gmail.com";
private static final String SSL_FACTORY =
"javax.net.ssl.SSLSocketFactory";
private static final String[] sendTo = {"xxx@gmail.com","xxx@yahoo.com"};
private static final String fileAttachment="D:\hai.txt";
public static void main(String args[]) throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
new GoogleTest().sendSSLMessage(sendTo, emailSubjectTxt,
emailMsgTxt, emailFromAddress);
System.out.println("Sucessfully Sent mail to All Users");
}
public void sendSSLMessage(String recipients[], String subject,
String message, String from) throws MessagingException {
boolean debug = true;
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxx@gmail.com", "give password of
gmail");
}
});
MimeMessage message1 =
new MimeMessage(session);
message1.setFrom(
new InternetAddress(from));
message1.addRecipient(
Message.RecipientType.TO,
new InternetAddress(recipients[0]));
message1.addRecipient(
Message.RecipientType.TO,
new InternetAddress(recipients[1]));
message1.setSubject(
"Hello JavaMail Attachment");
// create the message part
MimeBodyPart messageBodyPart =
new MimeBodyPart();
//fill message
messageBodyPart.setText("Hi");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source =
new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message1.setContent(multipart);
// Send the message
Transport.send( message1 );
}
}
Java Web Browser (Mini Project)
Code :
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import javax.swing.event.*;
public class Tarayici extends JFrame implements
ActionListener,HyperlinkListener
{
private JEditorPane webs;
private JScrollPane kay;
private JMenuBar menubar;
private JMenu menu,hakkimda;
private JMenuItem menukapa;
private Button kapat;
private Button yazdir;
private Button dugme;
private TextField kutu;
private URL url;
public Tarayici()
{
super("Tarayici");
setSize(950,700);
Container c=getContentPane();
dugme=new Button("Git");
dugme.addActionListener(this);
menubar=new JMenuBar();
menu=new JMenu("Dosya");
hakkimda=new JMenu("Hakkýmda");
hakkimda.addActionListener(this);
menukapa=new JMenuItem("Çýkýþ");
menukapa.addActionListener(this);
menu.add(menukapa);
menubar.add(menu);
menubar.add(hakkimda);
kapat=new Button("Kapat");
kapat.addActionListener(this);
yazdir=new Button("Geri");
yazdir.addActionListener(this);
kutu=new TextField("http://www.");
kutu.addActionListener(this);
webs=new JEditorPane();
webs.setEditable(false);
webs.addHyperlinkListener(this);
setJMenuBar(menubar);
c.setLayout(null);
kay=new JScrollPane(webs);
kay.setBounds(10,50,940,650);
kutu.setBounds(10,20,740,25);
dugme.setBounds(751,20,50,25);
kapat.setBounds(803,20,50,25);
yazdir.setBounds(855,20,50,25);
c.add(kapat);
c.add(kay);
c.add(dugme);
c.add(yazdir);
c.add(kutu);
show();
}
public void actionPerformed(ActionEvent e)
{
setTitle("Kachak Web Tarayici - Site Açýlýyor...");
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
Object kaynak=e.getSource();
String satir=kutu.getText();
if (kaynak==dugme || kaynak==kutu)
{
try {
webs.setPage(satir);
setTitle("Kachak Web Tarayici - Açýldý");
}
catch (IOException ei)
{
try {
webs.setPage("http://www.cmaeal.com/hata/hata.html");
kutu.setText("hata: sayfaYok");
}
catch (IOException se) {
System.out.print("Hata oldu..");
}
}
}
else if (kaynak==kapat)
{
System.exit(0);
}
else if (kaynak==hakkimda)
{
JOptionPane.showMessageDialog( this,"Sürüm 1.0","Yazan: Can
ÖKÇELIK",JOptionPane.INFORMATION_MESSAGE );
}
else if (kaynak==menukapa)
{
System.exit(0);
}
else if (kaynak==yazdir)
{
webs.setPage((String)yazdir.getEditor().getItem());
}
}
public void hyperlinkUpdate( HyperlinkEvent ea )
{
if ( ea.getEventType() ==
HyperlinkEvent.EventType.ACTIVATED )
{
try {
webs.setPage( ea.getURL().toString() );
kutu.setText(ea.getURL().toString());
}
catch (IOException ei)
{
try {
webs.setPage("http://www.cmaeal.com/hata/hata.html");
kutu.setText("hata: sayfaYok");
}
catch (IOException se) {
System.out.print("Hata oldu..");
}
}
}
}
public static void main(String[] args)
{
Tarayici t=new Tarayici();
t.setVisible(true);
}
}
Wednesday, December 2, 2009
create a datasource from a stream using JMF
import javax.media.protocol.ContentDescriptor;
import javax.media.protocol.PullDataSource;
import java.nio.ByteBuffer;
import java.io.IOException;
import javax.media.MediaLocator;
import javax.media.Duration;
import javax.media.Time;
/**
*
* @author Chad McMillan
*/
public class ByteBufferDataSource extends PullDataSource {
protected ContentDescriptor contentType;
protected SeekableStream[] sources;
protected boolean connected;
protected ByteBuffer anInput;
protected ByteBufferDataSource(){
}
/**
* Construct a
ByteBufferDataSource from a ByteBuffer.* @param source The
ByteBuffer that is used to create the* the
DataSource.*/
public ByteBufferDataSource(ByteBuffer input, String contentType) throws IOException {
anInput = input;
this.contentType = new ContentDescriptor(contentType);
connected = false;
}
/**
* Open a connection to the source described by
* the
ByteBuffer/CODE>.
*
*
* The connect method initiates communication with the source.
*
* @exception IOException Thrown if there are IO problems
* when connect is called.
*/
public void connect() throws java.io.IOException {
connected = true;
sources = new SeekableStream [1];
sources[0] = new SeekableStream(anInput);
}
/**
* Close the connection to the source described by the locator.
*
* The disconnect method frees resources used to maintain a
* connection to the source.
* If no resources are in use, disconnect is ignored.
* If stop hasn't already been called,
* calling disconnect implies a stop.
*
*/
public void disconnect() {
if(connected) {
sources[0].close();
connected = false;
}
}
/**
* Get a string that describes the content-type of the media
* that the source is providing.
*
* It is an error to call getContentType if the source is
* not connected.
*
* @return The name that describes the media content.
*/
public String getContentType() {
if( !connected) {
throw new java.lang.Error("Source is unconnected.");
}
return contentType.getContentType();
}
public Object getControl(String str) {
return null;
}
public Object[] getControls() {
return new Object[0];
}
public javax.media.Time getDuration() {
return Duration.DURATION_UNKNOWN;
}
/**
* Get the collection of streams that this source
* manages. The collection of streams is entirely
* content dependent. The MIME type of this
* DataSource provides the only indication of
* what streams can be available on this connection.
*
* @return The collection of streams for this source.
*/
public javax.media.protocol.PullSourceStream[] getStreams() {
if( !connected) {
throw new java.lang.Error("Source is unconnected.");
}
return sources;
}
/**
* Initiate data-transfer. The start method must be
* called before data is available.
*(You must call connect before calling start.)
*
* @exception IOException Thrown if there are IO problems with the source
* when start is called.
*/
public void start() throws IOException {
}
/**
* Stop the data-transfer.
* If the source has not been connected and started,
* stop does nothing.
*/
public void stop() throws IOException {
}
}
(and for your stream)
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.BufferUnderflowException;
import javax.media.protocol.PullSourceStream;
import javax.media.protocol.Seekable;
import javax.media.protocol.ContentDescriptor;
/**
*
* @author Chad McMillan
*/
public class SeekableStream implements PullSourceStream, Seekable {
protected ByteBuffer inputBuffer;
/**
* a flag to indicate EOF reached
*/
/** Creates a new instance of SeekableStream */
public SeekableStream(ByteBuffer byteBuffer) {
inputBuffer = byteBuffer;
this.seek((long)(0)); // set the ByteBuffer to to beginning
}
/**
* Find out if the end of the stream has been reached.
*
* @return Returns true if there is no more data.
*/
public boolean endOfStream() {
return (! inputBuffer.hasRemaining());
}
/**
* Get the current content type for this stream.
*
* @return The current ContentDescriptor for this stream.
*/
public ContentDescriptor getContentDescriptor() {
return null;
}
/**
* Get the size, in bytes, of the content on this stream.
*
* @return The content length in bytes.
*/
public long getContentLength() {
return inputBuffer.capacity();
}
/**
* Obtain the object that implements the specified
* Class or Interface
* The full class or interface name must be used.
*
*
* The control is not supported.
* null is returned.
*
* @return null.
*/
public Object getControl(String controlType) {
return null;
}
/**
* Obtain the collection of objects that
* control the object that implements this interface.
*
*
* No controls are supported.
* A zero length array is returned.
*
* @return A zero length array
*/
public Object[] getControls() {
Object[] objects = new Object[0];
return objects;
}
/**
* Find out if this media object can position anywhere in the
* stream. If the stream is not random access, it can only be repositioned
* to the beginning.
*
* @return Returns true if the stream is random access, false if the stream can only
* be reset to the beginning.
*/
public boolean isRandomAccess() {
return true;
}
/**
* Block and read data from the stream.
*
* Reads up to length bytes from the input stream into
* an array of bytes.
* If the first argument is null, up to
* length bytes are read and discarded.
* Returns -1 when the end
* of the media is reached.
*
* This method only returns 0 if it was called with
* a length of 0.
*
* @param buffer The buffer to read bytes into.
* @param offset The offset into the buffer at which to begin writing data.
* @param length The number of bytes to read.
* @return The number of bytes read, -1 indicating
* the end of stream, or 0 indicating read
* was called with length 0.
* @throws IOException Thrown if an error occurs while reading.
*/
public int read(byte[] buffer, int offset, int length) throws IOException {
// return n (number of bytes read), -1 (eof), 0 (asked for zero bytes)
if ( length == 0 )
return 0;
try {
inputBuffer.get(buffer,offset,length);
return length;
}
catch ( BufferUnderflowException E ) {
return -1;
}
}
public void close() {
}
/**
* Seek to the specified point in the stream.
* @param where The position to seek to.
* @return The new stream position.
*/
public long seek(long where) {
try {
inputBuffer.position((int)(where));
return where;
}
catch (IllegalArgumentException E) {
return this.tell(); // staying at the current position
}
}
/**
* Obtain the current point in the stream.
*/
public long tell() {
return inputBuffer.position();
}
/**
* Find out if data is available now.
* Returns true if a call to read would block
* for data.
*
* @return Returns true if read would block; otherwise
* returns false.
*/
public boolean willReadBlock() {
return (inputBuffer.remaining() == 0);
}
}
Mixing two audio files using Java Sound
So manually mixing the two or more audioinputstreams using some attitional api
note: each Audiofile length must be same
Download the Sample Sourcecode with API : Sample Source code ais_mixer.rar
Alternate Downloading Mirror :mirror(ais_mixer.rar)
or
Example:
first convert audiofile to audioinputstream
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
audioInputStream2 = AudioSystem.getAudioInputStream(soundFile2);
Create one collection list object using arraylist then add all audioinputstream's
Collection list=new ArrayList();
list.add(audioInputStream2);
list.add(audioInputStream);
then pass the audioformat and collection list to MixingAudioInputStream constructor
MixingAudioInputStream mixer=new MixingAudioInputStream(audioFormat, list);
finaly read data from mixed audioninputstream and give it to sourcedataline
nBytesRead =mixer.read(abData, 0,abData.length);
int nBytesWritten = line.write(abData, 0, nBytesRead);
Voice Chat Using Java
Step 1: first execute sender class
Step 2: Here after execute Tx class
Download Source : revoicechatusingjava.zip
Warning: Dont execute using sampe pc use different pc for each files otherwise it will be rise error ( mic already busy )
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
public class sender {
ServerSocket MyService;
Socket clientSocket = null;
BufferedInputStream input;
TargetDataLine targetDataLine;
BufferedOutputStream out;
ByteArrayOutputStream byteArrayOutputStream;
AudioFormat audioFormat;
SourceDataLine sourceDataLine;
byte tempBuffer[] = new byte[10000];
sender() throws LineUnavailableException{
try {
audioFormat = getAudioFormat();
DataLine.Info dataLineInfo = new DataLine.Info( SourceDataLine.class,audioFormat);
sourceDataLine = (SourceDataLine)
AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
MyService = new ServerSocket(500);
clientSocket = MyService.accept();
captureAudio();
input = new BufferedInputStream(clientSocket.getInputStream());
out=new BufferedOutputStream(clientSocket.getOutputStream());
while(input.read(tempBuffer)!=-1){
sourceDataLine.write(tempBuffer,0,10000);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private AudioFormat getAudioFormat(){
float sampleRate = 8000.0F;
int sampleSizeInBits = 16;
int channels = 1;
boolean signed = true;
boolean bigEndian = false;
return new AudioFormat(
sampleRate,
sampleSizeInBits,
channels,
signed,
bigEndian);
}
public static void main(String s[]) throws LineUnavailableException{
sender s2=new sender();
}
private void captureAudio() {
try {
Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
System.out.println("Available mixers:");
for (int cnt = 0; cnt < audioformat =" getAudioFormat();" datalineinfo =" new" mixer =" AudioSystem.getMixer(mixerInfo[3]);" targetdataline =" (TargetDataLine)" capturethread =" new" cnt =" targetDataLine.read(tempBuffer," stopcapture =" false;" out =" null;" in =" null;" sock =" null;" tx =" new" sock =" new" out =" new" in =" new" mixerinfo =" AudioSystem.getMixerInfo();" cnt =" 0;" audioformat =" getAudioFormat();" datalineinfo =" new" mixer =" AudioSystem.getMixer(mixerInfo[3]);" targetdataline =" (TargetDataLine)" capturethread =" new" datalineinfo1 =" new" sourcedataline =" (SourceDataLine)" playthread =" new" bytearrayoutputstream =" new" stopcapture =" false;" cnt =" targetDataLine.read(tempBuffer,"> 0) {
byteArrayOutputStream.write(tempBuffer, 0, cnt);
}
}
byteArrayOutputStream.close();
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
}
}
private AudioFormat getAudioFormat() {
float sampleRate = 8000.0F;
int sampleSizeInBits = 16;
int channels = 1;
boolean signed = true;
boolean bigEndian = false;
return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,
bigEndian);
}
class PlayThread extends Thread {
byte tempBuffer[] = new byte[10000];
public void run() {
try {
while (in.read(tempBuffer) != -1) {
sourceDataLine.write(tempBuffer, 0, 10000);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
----------------------------------------------
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.Socket;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
public class Tx {
boolean stopCapture = false;
ByteArrayOutputStream byteArrayOutputStream;
AudioFormat audioFormat;
TargetDataLine targetDataLine;
AudioInputStream audioInputStream;
BufferedOutputStream out = null;
BufferedInputStream in = null;
Socket sock = null;
SourceDataLine sourceDataLine;
public static void main(String[] args) {
Tx tx = new Tx();
tx.captureAudio();
}
private void captureAudio() {
try {
sock = new Socket("192.168.1.51", 500);
out = new BufferedOutputStream(sock.getOutputStream());
in = new BufferedInputStream(sock.getInputStream());
Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
System.out.println("Available mixers:");
for (int cnt = 0; cnt < audioformat =" getAudioFormat();" datalineinfo =" new" mixer =" AudioSystem.getMixer(mixerInfo[3]);" targetdataline =" (TargetDataLine)" capturethread =" new" datalineinfo1 =" new" sourcedataline =" (SourceDataLine)" playthread =" new" bytearrayoutputstream =" new" stopcapture =" false;" cnt =" targetDataLine.read(tempBuffer,"> 0) {
byteArrayOutputStream.write(tempBuffer, 0, cnt);
}
}
byteArrayOutputStream.close();
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
}
}
private AudioFormat getAudioFormat() {
float sampleRate = 8000.0F;
int sampleSizeInBits = 16;
int channels = 1;
boolean signed = true;
boolean bigEndian = false;
return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,
bigEndian);
}
class PlayThread extends Thread {
byte tempBuffer[] = new byte[10000];
public void run() {
try {
while (in.read(tempBuffer) != -1) {
sourceDataLine.write(tempBuffer, 0, 10000);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}