This is simple java program to copy a particular source file to destination directory. Just provide a source file (file which is to copy) and provide a destination directory where to file to be coppied, lets look at the code
/* CopyFile.java */
import java.io.*;
public class CopyFile
{
public void copy(File srcFile,File destDirectory)
{
try
{
String srcFilePath = srcFile.getPath();
String fileName = srcFilePath.substring(srcFilePath.lastIndexOf("\\")+1);
File destFile = new File(destDirectory.getPath()+"\\"+fileName);
InputStream inSrc = new FileInputStream(srcFile);
OutputStream outDest = new FileOutputStream(destFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inSrc.read(buffer)) > 0)
{
outDest.write(buffer, 0, bytesRead);
}
inSrc.close();
outDest.close();
System.out.println("File copy sucessfully : "+fileName);
}
catch (IOException ex)
{
System.out.println("Exception in copy : "+ex);
}
}
public static void main(String[] args)
{
CopyFile cf = new CopyFile();
cf.copy(new File("C:\\Downloads\\Test.zip"),new File("D:\\Work\\Files"));
}
}
Friday, December 25, 2009
Saturday, November 21, 2009
Java : Compare two dates using Date or Calendar class
Many times while programming in java we need to compare two dates, below are the two methods can be used to compare 2 dates, it can be done using either Date class or Calendar class. Below both program produces same output.
Method 1 : Using Date class
/* CompareDate.java */
import java.util.*;
import java.text.*;
public class CompareDate
{
public static void main(String[] args)
{
String date1 = "10-11-2009";//any date
String date2 = "10-11-2009";//any date
SimpleDateFormat formatterDate = new SimpleDateFormat("dd-MM-yyyy");
Date d1 = null;
Date d2 = null;
try
{
d1 = formatterDate.parse(date1);
d2 = formatterDate.parse(date2);
}
catch (Exception e)
{
System.out.println("Parse Exception :"+e);
}
int results = d1.compareTo(d2);
if(results > 0)
{
System.out.println("d1 "+date1+" is greater than d2 "+date2);
}
else if (results < 0)
{
System.out.println("d1 "+date1+" is less than d2 "+date2);
}
else //results = 0
{
System.out.println("d1 "+date1+" is equal to d2 "+date2);
}
}
}
Method 2 : Using Calendar class
/* CompareDate.java */
import java.util.*;
import java.text.*;
public class CompareDate
{
public static void main(String[] args)
{
String date1 = "15-11-2009";//any date
String date2 = "11-11-2009";//any date
SimpleDateFormat formatterDate = new SimpleDateFormat("dd-MM-yyyy");
Date d1 = null;
Date d2 = null;
try
{
d1 = formatterDate.parse(date1);
d2 = formatterDate.parse(date2);
}
catch (Exception e)
{
System.out.println("Parse Exception :"+e);
}
Calendar ss=Calendar.getInstance();
Calendar ee=Calendar.getInstance();
ss.setTime(d1);
ee.setTime(d2);
if(d1.after(d2))
{
System.out.println("d1 "+date1+" is greater than d2 "+date2);
}
else if (d1.before(d2))
{
System.out.println("d1 "+date1+" is less than d2 "+date2);
}
else //d1.equals(d2)
{
System.out.println("d1 "+date1+" is equal to d2 "+date2);
}
}
}
Method 1 : Using Date class
/* CompareDate.java */
import java.util.*;
import java.text.*;
public class CompareDate
{
public static void main(String[] args)
{
String date1 = "10-11-2009";//any date
String date2 = "10-11-2009";//any date
SimpleDateFormat formatterDate = new SimpleDateFormat("dd-MM-yyyy");
Date d1 = null;
Date d2 = null;
try
{
d1 = formatterDate.parse(date1);
d2 = formatterDate.parse(date2);
}
catch (Exception e)
{
System.out.println("Parse Exception :"+e);
}
int results = d1.compareTo(d2);
if(results > 0)
{
System.out.println("d1 "+date1+" is greater than d2 "+date2);
}
else if (results < 0)
{
System.out.println("d1 "+date1+" is less than d2 "+date2);
}
else //results = 0
{
System.out.println("d1 "+date1+" is equal to d2 "+date2);
}
}
}
Method 2 : Using Calendar class
/* CompareDate.java */
import java.util.*;
import java.text.*;
public class CompareDate
{
public static void main(String[] args)
{
String date1 = "15-11-2009";//any date
String date2 = "11-11-2009";//any date
SimpleDateFormat formatterDate = new SimpleDateFormat("dd-MM-yyyy");
Date d1 = null;
Date d2 = null;
try
{
d1 = formatterDate.parse(date1);
d2 = formatterDate.parse(date2);
}
catch (Exception e)
{
System.out.println("Parse Exception :"+e);
}
Calendar ss=Calendar.getInstance();
Calendar ee=Calendar.getInstance();
ss.setTime(d1);
ee.setTime(d2);
if(d1.after(d2))
{
System.out.println("d1 "+date1+" is greater than d2 "+date2);
}
else if (d1.before(d2))
{
System.out.println("d1 "+date1+" is less than d2 "+date2);
}
else //d1.equals(d2)
{
System.out.println("d1 "+date1+" is equal to d2 "+date2);
}
}
}
Labels:
Compare Files
Tuesday, October 20, 2009
Java : Simple XML Parser
/* SimpleXmlParser.java */
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class SimpleXmlParser
{
public static void main(String[] args)
{
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document dom = null;
try
{
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse("xmlFile.xml");
//get the root elememt
Element docEle = dom.getDocumentElement();
//get a nodelist of slot elements
NodeList nl = docEle.getElementsByTagName("Employee");
if(nl != null && nl.getLength() > 0)
{
for(int i = 0 ; i < nl.getLength();i++)
{
System.out.println("--Employee--");
Element el = (Element)nl.item(i);
System.out.println("Name : "+getTextValue(el,"Name"));
System.out.println("Designation : "+getTextValue(el,"Designation"));
System.out.println("Department : "+getTextValue(el,"Department"));
}
}
}
catch(Exception ex)
{
System.out.println("Exception : "+ex);
}
}
public static String getTextValue(Element ele, String tagName)
{
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0)
{
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
}
/* xmlFile.xml */
<AllEmployee>
<Employee>
<Name>Ram</Name>
<Designation>Programmer</Designation>
<Department>Development</Department>
</Employee>
<Employee>
<Name>Shyam</Name>
<Designation>TL</Designation>
<Department>Finanace</Department>
</Employee>
<Employee>
<Name>Geeta</Name>
<Designation>Manager</Designation>
<Department>HR</Department>
</Employee>
</AllEmployee>
Output
--Employee--
Name : Ram
Designation : Programmer
Department : Development
--Employee--
Name : Shyam
Designation : TL
Department : Finanace
--Employee--
Name : Geeta
Designation : Manager
Department : HR
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class SimpleXmlParser
{
public static void main(String[] args)
{
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document dom = null;
try
{
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse("xmlFile.xml");
//get the root elememt
Element docEle = dom.getDocumentElement();
//get a nodelist of slot elements
NodeList nl = docEle.getElementsByTagName("Employee");
if(nl != null && nl.getLength() > 0)
{
for(int i = 0 ; i < nl.getLength();i++)
{
System.out.println("--Employee--");
Element el = (Element)nl.item(i);
System.out.println("Name : "+getTextValue(el,"Name"));
System.out.println("Designation : "+getTextValue(el,"Designation"));
System.out.println("Department : "+getTextValue(el,"Department"));
}
}
}
catch(Exception ex)
{
System.out.println("Exception : "+ex);
}
}
public static String getTextValue(Element ele, String tagName)
{
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0)
{
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
}
/* xmlFile.xml */
<AllEmployee>
<Employee>
<Name>Ram</Name>
<Designation>Programmer</Designation>
<Department>Development</Department>
</Employee>
<Employee>
<Name>Shyam</Name>
<Designation>TL</Designation>
<Department>Finanace</Department>
</Employee>
<Employee>
<Name>Geeta</Name>
<Designation>Manager</Designation>
<Department>HR</Department>
</Employee>
</AllEmployee>
Output
--Employee--
Name : Ram
Designation : Programmer
Department : Development
--Employee--
Name : Shyam
Designation : TL
Department : Finanace
--Employee--
Name : Geeta
Designation : Manager
Department : HR
Labels:
XML
Friday, October 16, 2009
Java : Implement console in textarea using swing or awt
Program to implement output console using JTextArea of swing or TextArea of awt. Here all output log ie (System.out.println("")) is redirected to textarea rather than console.
Here is the complete code, directly you can run this code and see output.
/* ImplementConsole.java */
import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.io.*;
public class ImplementConsole extends JFrame
{
JTextArea console;
JScrollPane sp_console;
ImplementConsole()
{
setSize(700,350);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
console = new javax.swing.JTextArea();
console.setColumns(50);
console.setRows(15);
console.setText("Console Output...");
sp_console = new javax.swing.JScrollPane(console);
add(sp_console);
System.setOut(new PrintStream(new JTextAreaOutputStream(console)));
System.setErr(new PrintStream(new JTextAreaOutputStream(console)));
//starting new Thread for log writing
new Thread(new Runnable()
{
public void run()
{ try
{
writeLog();
}
catch (Exception ie)
{ }
}
}).start();
}
//inner class
public class JTextAreaOutputStream extends OutputStream
{
JTextArea ta;
public JTextAreaOutputStream(JTextArea t)
{
super();
ta = t;
}
public void write(int i)
{
ta.append(Character.toString((char)i));
}
public void write(char[] buf, int off, int len)
{
String s = new String(buf, off, len);
ta.append(s);
}
}
//function to write console log
public void writeLog()
{
for(int i=0; i< 10000; i++)
{
System.out.println("Console output : "+i);
// Make sure the last line is always visible
console.setCaretPosition(console.getDocument().getLength());
//just taking pause of 50ms
try
{
Thread.currentThread().sleep(50);
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}
//to flush console log after specific number of lines.
if(console.getLineCount() > 1000)
console.setText("");
}
}
public static void main(String[] args)
{
JFrame obj = new ImplementConsole();
obj.setVisible(true);
}
}
Output
Here is the complete code, directly you can run this code and see output.
/* ImplementConsole.java */
import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.io.*;
public class ImplementConsole extends JFrame
{
JTextArea console;
JScrollPane sp_console;
ImplementConsole()
{
setSize(700,350);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
console = new javax.swing.JTextArea();
console.setColumns(50);
console.setRows(15);
console.setText("Console Output...");
sp_console = new javax.swing.JScrollPane(console);
add(sp_console);
System.setOut(new PrintStream(new JTextAreaOutputStream(console)));
System.setErr(new PrintStream(new JTextAreaOutputStream(console)));
//starting new Thread for log writing
new Thread(new Runnable()
{
public void run()
{ try
{
writeLog();
}
catch (Exception ie)
{ }
}
}).start();
}
//inner class
public class JTextAreaOutputStream extends OutputStream
{
JTextArea ta;
public JTextAreaOutputStream(JTextArea t)
{
super();
ta = t;
}
public void write(int i)
{
ta.append(Character.toString((char)i));
}
public void write(char[] buf, int off, int len)
{
String s = new String(buf, off, len);
ta.append(s);
}
}
//function to write console log
public void writeLog()
{
for(int i=0; i< 10000; i++)
{
System.out.println("Console output : "+i);
// Make sure the last line is always visible
console.setCaretPosition(console.getDocument().getLength());
//just taking pause of 50ms
try
{
Thread.currentThread().sleep(50);
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}
//to flush console log after specific number of lines.
if(console.getLineCount() > 1000)
console.setText("");
}
}
public static void main(String[] args)
{
JFrame obj = new ImplementConsole();
obj.setVisible(true);
}
}
Output
Java : Time elapsed counter using swing
Java program that calculates time elapsed from start time, using this you can implement stop watch. Logic is simple just get start time (time when program started) and increment the time counter by current time minus start time ie (elapsedTime = currentTime - starTime).
Here is the complete tested code, directly you can run this code and see output.
/* TimeElapsed.java */
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.text.*;
public class TimeElapsed extends JFrame
{
JLabel time;
long startTime = System.currentTimeMillis();
TimeElapsed()
{
setSize(380,200);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
time = new JLabel("");
time.setFont(new Font("SansSerif",Font.BOLD, 36));
time.setForeground(Color.MAGENTA);
add(time);
//starting new Thread which will update time
new Thread(new Runnable()
{
public void run()
{ try
{
updateTime();
}
catch (Exception ie)
{ }
}
}).start();
}
public void updateTime()
{
try
{
while(true)
{
//geting Time in desire format
time.setText(getTimeElapsed());
//Thread sleeping for 1 sec
Thread.currentThread().sleep(1000);
}
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}
}
public String getTimeElapsed()
{
long elapsedTime = System.currentTimeMillis() - startTime;
elapsedTime = elapsedTime / 1000;
String seconds = Integer.toString((int)(elapsedTime % 60));
String minutes = Integer.toString((int)((elapsedTime % 3600) / 60));
String hours = Integer.toString((int)(elapsedTime / 3600));
if (seconds.length() < 2)
seconds = "0" + seconds;
if (minutes.length() < 2)
minutes = "0" + minutes;
if (hours.length() < 2)
hours = "0" + hours;
return hours+":"+minutes+":"+seconds;
}
public static void main(String[] args)
{
JFrame obj = new TimeElapsed();
obj.setVisible(true);
}
}
Output
Here is the complete tested code, directly you can run this code and see output.
/* TimeElapsed.java */
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.text.*;
public class TimeElapsed extends JFrame
{
JLabel time;
long startTime = System.currentTimeMillis();
TimeElapsed()
{
setSize(380,200);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
time = new JLabel("");
time.setFont(new Font("SansSerif",Font.BOLD, 36));
time.setForeground(Color.MAGENTA);
add(time);
//starting new Thread which will update time
new Thread(new Runnable()
{
public void run()
{ try
{
updateTime();
}
catch (Exception ie)
{ }
}
}).start();
}
public void updateTime()
{
try
{
while(true)
{
//geting Time in desire format
time.setText(getTimeElapsed());
//Thread sleeping for 1 sec
Thread.currentThread().sleep(1000);
}
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}
}
public String getTimeElapsed()
{
long elapsedTime = System.currentTimeMillis() - startTime;
elapsedTime = elapsedTime / 1000;
String seconds = Integer.toString((int)(elapsedTime % 60));
String minutes = Integer.toString((int)((elapsedTime % 3600) / 60));
String hours = Integer.toString((int)(elapsedTime / 3600));
if (seconds.length() < 2)
seconds = "0" + seconds;
if (minutes.length() < 2)
minutes = "0" + minutes;
if (hours.length() < 2)
hours = "0" + hours;
return hours+":"+minutes+":"+seconds;
}
public static void main(String[] args)
{
JFrame obj = new TimeElapsed();
obj.setVisible(true);
}
}
Output
Subscribe to:
Posts (Atom)