In this post, you learn to do manipulations on the Array data structure. Array is a basic data structure that can perhaps be found in all programming languages. It generally is used to
store homogeneous values. Searching and sorting are actions that are commonly performed on the array. You can write your own code to sort, search, copy the array or compare the array with another array. However, it wastes your time and the performances of the actions or operations might not good.
The Arrays class is utility that is shipped with the Java standard API. It can be used to sort, search, copy or compare arrays easily. To sort the array, you can use the sort method. This method will arrange the elements of the array in ascending order. If you want to sort the array in descending order, you need to implement the Comparator interface. The post about Collections class has an example of implementing the Comparator interface in list sorting operations. The sort method of the Arrays class accepts one argument which is the array that you want to sort.
import java.util.Arrays;
public class ArrayManipulation {
public static void main(String[] args){
//create an integer array
Integer[] nums={12,43,45,78,56,10,35,89};
//sort the array in ascending order
Arrays.sort(nums);
for(int i:nums){
System.out.println(i);
}
}
}
You will use the binarySearch method to search an element of the array. It returns the index of the element if it is found in the array. Otherwise, it returns a negative value. The binary search algorithm is proved to be the fastest searching technique for the array. Before using the binarySearch method to search for an element of the array, you have to sort the array. This method accepts two arguments. One is the array object and another one is the element that you want to search for.
//search an element of the array
int pos=Arrays.binarySearch(nums,56);
if(pos>0)
System.out.println("Found at "+pos);
else{
System.out.println("Not found"+pos);
}
The Arrays class has copyOf and copyOfRange methods that you can use to copy elements of an array to another array. You will use the copyOf method to copy a number of elements of the array by starting from the first element. This method accepts two arguments. One is the array object and another one is the number of elements to be copies from the original array. You will get NullPointerException error if the number of elements to be copies is greater than the size of the original array. If you want to copy the elements by starting from a specified index rather than from the beginning or first element of the array, the copyOfRange method can help you. This method accepts three arguments. The first argument is the array object. The second argument is the start or from index and the last argument is the end or to index. The start index must be between 0 and size or length of the array. The end or to index must be greater than or equal the start index. If the end index is greater than the length of the array, you will get NullPointerException error. The start index is inclusive while end index is exclusive.
//copy the first three elements from nums to numsCopy
Integer[] numsCopy=Arrays.copyOf(nums, 3);
for(int i:numsCopy){
System.out.println(i);
}
//copy all elements from nums to newnums
Integer[] newnums=Arrays.copyOf(nums,nums.length);
for(int i:newnums){
System.out.println(i);
}
//copy a specified range of elements from nums
Integer[] arange=Arrays.copyOfRange(nums, 2, 7);
for(int i:arange){
System.out.println(i);
}
The Arrays class also provides a method that you can use to compare two arrays for equality. This method is called equals. The equals method accepts two array arguments. It returns true if the two arrrays are equal. Otherwise, it returns false.
Integer[] nums={12,43,45,78,56,10,35,89};
//copy all elements from nums to newnums
Integer[] newnums=Arrays.copyOf(nums,nums.length);
//check for equality
boolean b=Arrays.equals(nums, newnums);
if(b)
System.out.println("The two arrays are equal.");
else
System.out.println("The two arrays are not equal.");
This site provides you the opportunity to learn Java programming language by programs.
Wednesday, October 23, 2013
Monday, October 21, 2013
Date Diff and Date Add
Finding the number of years, months, days, minutes, seconds, or milliseconds between two date times can be a hard task for beginners. In this post, you will learn how to calculate the difference in days between two date times and to calculate the future and past dates from the current date. These tasks can be done simply by using the Joda-Time library. It is the most useful library to work with date and times. You will need to download this library from Joda-Time website. You will get a zip file. Please extract the zip file to a folder that you can file.
To use the Joda-Time library in your code, you need to add the jar file (joda-time-2.2.jar) to the build path of the Eclipse. You can follow the step below to add the library to the project in Eclipse.
1. From the Project menu, select Properties.
2. On the properties window, select Java Build Path. Then select Add External Jars...
3. Browse to find the jar file that you have extracted. Then click OK.
If you are using the Windows' command prompt to compile and run your java program, you will need to the add the path of the jar file to the CLASSPATH by going to the Control Panel->System->Advanced System Settings. In the System Properties dialog, select Environment Variables. In the box under User variables, double-click CLASSPATH. Then append the path of the jar file to the Variable value text box. You will use the semi-colon (;) to separate each path entry.
Now you are ready to use the Jodatime library. To calculate the difference between two date times, you can use the Years.Years.yearsBetween, Months.monthsBetween, Days.daysBetween, Hours.hoursBetween, Minutes.minutesBetween, Seconds.secondsBetween methods. The example code below calculates the days and hours between the current and another future date.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
public class DateDiff {
public static void main(String[] args){
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyyy");
Date futureDate=null;
Date today = Calendar.getInstance().getTime();
try{
futureDate= formatter.parse("30-10-2013");
}
catch(ParseException pe) {
System.out.println("Parser Exception");
}
Days days = Days.daysBetween(new DateTime(today),new DateTime(futureDate));
Hours hours=Hours.hoursBetween(new DateTime(today), new DateTime(futureDate));
System.out.println(" Days Between " + today + " and " + futureDate + " :" + days.getDays());
System.out.println(" Hours Between " + today + " and " + futureDate + " :" + hours.getHours());
}
}
If you would like to calculate the future date by adding a number of years, months, days, hours, minutes, seconds, or milliseconds to the current date, you will use the plusYears, plusMonths, plusDays, plusHours, plusMinutes, plusSeconds, or plusMillis methods of the DateTime class. Similarly, to find the past date, you can use the minusYears, minusMonths, minusDays, minusHours, minusMinutes, minusSeconds, or minusMillis methods. Read the example code below.
import java.util.Calendar;
import java.util.Date;
import org.joda.time.DateTime;
public class DateAdd{
public static void main(String[] args){
Date today = Calendar.getInstance().getTime();
DateTime dt=new DateTime(today);
DateTime futureDate=dt.plusDays(2); //add two days to the current date
System.out.println("The future date is "+futureDate);
}
}
To use the Joda-Time library in your code, you need to add the jar file (joda-time-2.2.jar) to the build path of the Eclipse. You can follow the step below to add the library to the project in Eclipse.
1. From the Project menu, select Properties.
2. On the properties window, select Java Build Path. Then select Add External Jars...
3. Browse to find the jar file that you have extracted. Then click OK.
If you are using the Windows' command prompt to compile and run your java program, you will need to the add the path of the jar file to the CLASSPATH by going to the Control Panel->System->Advanced System Settings. In the System Properties dialog, select Environment Variables. In the box under User variables, double-click CLASSPATH. Then append the path of the jar file to the Variable value text box. You will use the semi-colon (;) to separate each path entry.
Now you are ready to use the Jodatime library. To calculate the difference between two date times, you can use the Years.Years.yearsBetween, Months.monthsBetween, Days.daysBetween, Hours.hoursBetween, Minutes.minutesBetween, Seconds.secondsBetween methods. The example code below calculates the days and hours between the current and another future date.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
public class DateDiff {
public static void main(String[] args){
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyyy");
Date futureDate=null;
Date today = Calendar.getInstance().getTime();
try{
futureDate= formatter.parse("30-10-2013");
}
catch(ParseException pe) {
System.out.println("Parser Exception");
}
Days days = Days.daysBetween(new DateTime(today),new DateTime(futureDate));
Hours hours=Hours.hoursBetween(new DateTime(today), new DateTime(futureDate));
System.out.println(" Days Between " + today + " and " + futureDate + " :" + days.getDays());
System.out.println(" Hours Between " + today + " and " + futureDate + " :" + hours.getHours());
}
}
If you would like to calculate the future date by adding a number of years, months, days, hours, minutes, seconds, or milliseconds to the current date, you will use the plusYears, plusMonths, plusDays, plusHours, plusMinutes, plusSeconds, or plusMillis methods of the DateTime class. Similarly, to find the past date, you can use the minusYears, minusMonths, minusDays, minusHours, minusMinutes, minusSeconds, or minusMillis methods. Read the example code below.
import java.util.Calendar;
import java.util.Date;
import org.joda.time.DateTime;
public class DateAdd{
public static void main(String[] args){
Date today = Calendar.getInstance().getTime();
DateTime dt=new DateTime(today);
DateTime futureDate=dt.plusDays(2); //add two days to the current date
System.out.println("The future date is "+futureDate);
}
}
|
|
Saturday, October 19, 2013
Transparent Window
Sometimes, you might want to make your window transparent so that any thing behind the window can be seen. For older Java versions under Java 7, you can not simply make the window transparent. In Java 7, it works. In the example code below, the window created by the JFrame component is transparent.
There are two methods of the JFrame class that you will use to make the window transparent. The first method is setUndecorated. Before you can change the transparency of the window, it is required the window undecorated (e.g without border, title). By providing the true value to the setUndecorated method, the window is now undecorated. You should note that the window can be undecorated when it is not displayable. So, you must call the the setVisible method to show the window after calling the setUndecorated method. Otherwise, an error will occur.
The second method is setOpacity. This method accepts the opacity value between 0.0 and 1.0. To make the window completely transparent, you will supply 0.0 to this method. In default, this value is 1.0 representing the complete opaque window (not transparent).
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class WindowTran {
public static void main(String[] args){
JFrame window=new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(new Dimension(400,300));
window.setLocationRelativeTo(null);
window.setUndecorated(true);
window.setOpacity(0.5f);
Container cont=window.getContentPane();
JButton bt=new JButton(new Action("", new ImageIcon("d:/gmaptr.png")));
cont.add(bt,BorderLayout.CENTER);
window.setVisible(true);
}
static class Action extends AbstractAction{
Action(String title){
super(title);
}
Action(String title, Icon image){
super(title, image);
}
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
}
There are two methods of the JFrame class that you will use to make the window transparent. The first method is setUndecorated. Before you can change the transparency of the window, it is required the window undecorated (e.g without border, title). By providing the true value to the setUndecorated method, the window is now undecorated. You should note that the window can be undecorated when it is not displayable. So, you must call the the setVisible method to show the window after calling the setUndecorated method. Otherwise, an error will occur.
The second method is setOpacity. This method accepts the opacity value between 0.0 and 1.0. To make the window completely transparent, you will supply 0.0 to this method. In default, this value is 1.0 representing the complete opaque window (not transparent).
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class WindowTran {
public static void main(String[] args){
JFrame window=new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(new Dimension(400,300));
window.setLocationRelativeTo(null);
window.setUndecorated(true);
window.setOpacity(0.5f);
Container cont=window.getContentPane();
JButton bt=new JButton(new Action("", new ImageIcon("d:/gmaptr.png")));
cont.add(bt,BorderLayout.CENTER);
window.setVisible(true);
}
static class Action extends AbstractAction{
Action(String title){
super(title);
}
Action(String title, Icon image){
super(title, image);
}
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
}
Wednesday, October 16, 2013
Collections
Collections is a useful class in Java that can be used with List data structures such as ArrayList, LinkedList, Stack, Vector, etc. The Collections has static methods that you can use to sort the List, search an element of the List, count the number of duplicate elements in the List (frequency), reverse the List, check whether a list contains in another list, and find max and min elements of the List.
To sort the elements in the List, you will use the sort method. This method will take the list object that you want to sort. Naturally the sort method sorts the List in ascending order (from small to big). In the example code below, ten random numbers from 1 to 6 are generated and added to the ArrayList obbject, IntList. The IntList is sorted in ascending order by calling the sort method of the Collections class.
ArrayList<Integer> IntList=new ArrayList<Integer>();
Random random=new Random();
for(int i=0;i<10;i++){
IntList.add(1+Math.abs(random.nextInt())%6);
}
Collections.sort(IntList);
System.out.println(IntList);
If you want to control the sort orders of the List, you need to implement the Comparator interface. This interface has the compare method that is used to compare elements of the List. The return from this method will instruct the Collections to order the List in ascending or descending order. The following Com class implement is example of implementing the Comparator interface. You can use the Com class to order the List in ascending or descending. The Com class has two constructors. One is the default constructor. By using the default constructor, the List will be sorted in ascending order. The second constructor allows you to specify an order value to the Com class. To sort the List descending order, you will provide a negative number. By supplying the positive number, the List will be sorted in ascending order the same as using the default constructor. If you provide zero, the List will not be sorted.
class Com implements Comparator<Object>{
int order=1;
//default constructor
Com(){
}
Com(int order){
this.order=order;
}
public int compare(Object x, Object y){
if (x.toString().compareTo(y.toString())>0) return order;
else if (x.toString().compareTo(y.toString())<0) return -1*order;
else return 0;
}
}
To use the Com class, you need to create its object and supply it to the sort method of the Collections class.
Collections.sort(IntList, new Com(-1)); //sort List in descending order
System.out.println(IntList)
To search an element of a List object, you will use the binarySearch method. This method uses the binary search algorithm to find the specified element in the List. In List data structures, the element of the List can be located very fast by using the binary search technique when the List is sorted. So, you need to sort the List before using the binarySearch method. The BinarySearch method returns the position of the matched element in the List. If the specified element is not found in the list, it returns -1. The example code below returns the position of the 3 element of the list if it is found.
int pos=Collections.binarySearch(IntList, 3);
In addition to search for a specific element of the List, you can search for a sub list in the List. In the example code below, the sub list, SubList contains two elements--2 and 3. This sub list will be searched in the IntList by using lastIndexOfSubList method. If the sub list, SubList is in the list, IntList, its position will be returned otherwise the -1 value is returned.
ArrayList<Integer> SubList=new ArrayList<Integer>();
SubList.add(2);
SubList.add(3);
int pos=Collections.lastIndexOfSubList(IntList, SubList);
You can count the number of duplicate elements in the List by using the frequency method. This method takes two arguments. One is the List object another is the element that you want to count. The example code below counts the number of the 2 elements that occur in the List.
int count=Collections.frequency(x, 2);
To reserve the List, you will use the reverse method. This method takes only the List object that you want to reverse.
Collections.reverse(IntList);
The Collections also provides the max and min methods to find the maximum and minimum elements of the List. To find the max and min elements of the IntList, you can write as shown below.
int maxele=Collections.max(IntList);
int minele=Collections.min(IntList);
To sort the elements in the List, you will use the sort method. This method will take the list object that you want to sort. Naturally the sort method sorts the List in ascending order (from small to big). In the example code below, ten random numbers from 1 to 6 are generated and added to the ArrayList obbject, IntList. The IntList is sorted in ascending order by calling the sort method of the Collections class.
ArrayList<Integer> IntList=new ArrayList<Integer>();
Random random=new Random();
for(int i=0;i<10;i++){
IntList.add(1+Math.abs(random.nextInt())%6);
}
Collections.sort(IntList);
System.out.println(IntList);
If you want to control the sort orders of the List, you need to implement the Comparator interface. This interface has the compare method that is used to compare elements of the List. The return from this method will instruct the Collections to order the List in ascending or descending order. The following Com class implement is example of implementing the Comparator interface. You can use the Com class to order the List in ascending or descending. The Com class has two constructors. One is the default constructor. By using the default constructor, the List will be sorted in ascending order. The second constructor allows you to specify an order value to the Com class. To sort the List descending order, you will provide a negative number. By supplying the positive number, the List will be sorted in ascending order the same as using the default constructor. If you provide zero, the List will not be sorted.
class Com implements Comparator<Object>{
int order=1;
//default constructor
Com(){
}
Com(int order){
this.order=order;
}
public int compare(Object x, Object y){
if (x.toString().compareTo(y.toString())>0) return order;
else if (x.toString().compareTo(y.toString())<0) return -1*order;
else return 0;
}
}
To use the Com class, you need to create its object and supply it to the sort method of the Collections class.
Collections.sort(IntList, new Com(-1)); //sort List in descending order
System.out.println(IntList)
To search an element of a List object, you will use the binarySearch method. This method uses the binary search algorithm to find the specified element in the List. In List data structures, the element of the List can be located very fast by using the binary search technique when the List is sorted. So, you need to sort the List before using the binarySearch method. The BinarySearch method returns the position of the matched element in the List. If the specified element is not found in the list, it returns -1. The example code below returns the position of the 3 element of the list if it is found.
int pos=Collections.binarySearch(IntList, 3);
In addition to search for a specific element of the List, you can search for a sub list in the List. In the example code below, the sub list, SubList contains two elements--2 and 3. This sub list will be searched in the IntList by using lastIndexOfSubList method. If the sub list, SubList is in the list, IntList, its position will be returned otherwise the -1 value is returned.
ArrayList<Integer> SubList=new ArrayList<Integer>();
SubList.add(2);
SubList.add(3);
int pos=Collections.lastIndexOfSubList(IntList, SubList);
You can count the number of duplicate elements in the List by using the frequency method. This method takes two arguments. One is the List object another is the element that you want to count. The example code below counts the number of the 2 elements that occur in the List.
int count=Collections.frequency(x, 2);
To reserve the List, you will use the reverse method. This method takes only the List object that you want to reverse.
Collections.reverse(IntList);
The Collections also provides the max and min methods to find the maximum and minimum elements of the List. To find the max and min elements of the IntList, you can write as shown below.
int maxele=Collections.max(IntList);
int minele=Collections.min(IntList);
Monday, October 14, 2013
StringBuilder
StringBuilder class provides more
power over the normal String class. It allows you modify the content of a string easily. With the StringBuilder class, you can insert different types of values in to a string at any position, delete a part of the string, reverse string, etc. These operations are not found in the String class.
To insert a value (a character, an array of characters, a number, or string) to any position of the string wrapped by the StringBuilder object, you can use the following insert methods as shown below:
-insert(int position, char c) inserts the character, c in to the string.
-insert (int position, char[] cs) inserts the array of characters, cs in to the string.
-insert(int position, int i) inserts the integer value, i in to the string.
-insert(int position, long l) inserts the long integer value, l to the string.
-insert(int position, double d) inserts the double value, d to the string.
-insert(int position, String str) inserts the string value, str to the string.
Example:
String oldString="StringBuilder Java";
StringBuilder sb=new StringBuilder(oldString);
sb.insert(sb.lastIndexOf(" "), " in"); //insert in to the string
System.out.println(sb);
Note: The lastIndexOf(String str) method returns the last position of the argument str in the string. To convert back from the StringBuilder object to a normal String object, you will use the toString() method of the StringBuilder.
If you want to delete a part of the string, you will use the delete(int start,int end) method. Similarly to the insert method, the delete method will modified the content of StringBuilder object.
Example:
String oldString="StringBuilder Java";
StringBuilder sb=new StringBuilder(oldString);
sb.delete(0, sb.lastIndexOf(" ")); //remove the StringBuilder from the string
System.out.println(sb);
Besides insert, and delete method, the StringBuilder class has the reverse method that can be used to reserve the sequence of characters in the string. This method is also not found in the normal String class.
Example:
String oldString="StringBuilder Java";
StringBuilder sb=new StringBuilder(oldString);
sb.reverse();
System.out.println(sb);
To insert a value (a character, an array of characters, a number, or string) to any position of the string wrapped by the StringBuilder object, you can use the following insert methods as shown below:
-insert(int position, char c) inserts the character, c in to the string.
-insert (int position, char[] cs) inserts the array of characters, cs in to the string.
-insert(int position, int i) inserts the integer value, i in to the string.
-insert(int position, long l) inserts the long integer value, l to the string.
-insert(int position, double d) inserts the double value, d to the string.
-insert(int position, String str) inserts the string value, str to the string.
Example:
String oldString="StringBuilder Java";
StringBuilder sb=new StringBuilder(oldString);
sb.insert(sb.lastIndexOf(" "), " in"); //insert in to the string
System.out.println(sb);
Note: The lastIndexOf(String str) method returns the last position of the argument str in the string. To convert back from the StringBuilder object to a normal String object, you will use the toString() method of the StringBuilder.
If you want to delete a part of the string, you will use the delete(int start,int end) method. Similarly to the insert method, the delete method will modified the content of StringBuilder object.
Example:
String oldString="StringBuilder Java";
StringBuilder sb=new StringBuilder(oldString);
sb.delete(0, sb.lastIndexOf(" ")); //remove the StringBuilder from the string
System.out.println(sb);
Besides insert, and delete method, the StringBuilder class has the reverse method that can be used to reserve the sequence of characters in the string. This method is also not found in the normal String class.
Example:
String oldString="StringBuilder Java";
StringBuilder sb=new StringBuilder(oldString);
sb.reverse();
System.out.println(sb);
Thursday, October 10, 2013
Upload file to FTP server
In this post, you learn to write Java code to upload a file from your local disk to a remote FTP server. Java does not provide an API to connect and upload files to or download files from a remote FTP server. In this example code, the API used to connect and upload the file to the FTP server is commons-net. The API contains a class called FTPClient that can be used to upload files to or download files from the FTP server. The commons-net API can be downloaded from Apache website.
In the example code below, the FTPClient object is created and its connect(String ftphostname) is invoked to connect to the remote FTP server. You need to supply the name of your FTP server to this method. The login(String username,String password) method will log in to the remote server. Normally, for file transferring between the client and server, you need to set the connection mode to passive mode by using the enterLocalPassiveMode() method. For the file transferring between a server and another server, you will use the enterRemoteActiveMode() instead. The default directory of the server to upload the file to is the root directory (/). You can specify a directory to upload the file to by using the changeWorkingDirectory(String dirpath).
Before transferring the files to the server, you should check whether you connect and login to the server successfully by using the isPositiveCompletion(int replyCode) method. If this method return true, you can upload the files to the server by using the storeFile(String remoteFileName,InputStream is) method. This method will copy data from the InputStream object and place it on the server with the name specified by the remoteFileName argument. After the upload task completes, you can log out and disconnect from the server by using the logout() and disconnect() method.
To avoid this problem or error, you need to turn off the Windows Firewall (Control Panel-> Windows Firewall). Then run the the Java program again.
In the example code below, the FTPClient object is created and its connect(String ftphostname) is invoked to connect to the remote FTP server. You need to supply the name of your FTP server to this method. The login(String username,String password) method will log in to the remote server. Normally, for file transferring between the client and server, you need to set the connection mode to passive mode by using the enterLocalPassiveMode() method. For the file transferring between a server and another server, you will use the enterRemoteActiveMode() instead. The default directory of the server to upload the file to is the root directory (/). You can specify a directory to upload the file to by using the changeWorkingDirectory(String dirpath).
Before transferring the files to the server, you should check whether you connect and login to the server successfully by using the isPositiveCompletion(int replyCode) method. If this method return true, you can upload the files to the server by using the storeFile(String remoteFileName,InputStream is) method. This method will copy data from the InputStream object and place it on the server with the name specified by the remoteFileName argument. After the upload task completes, you can log out and disconnect from the server by using the logout() and disconnect() method.
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class HttpHeaders {
public static void main(String[] args){
ftpUpload();
}
public static void ftpUpload(){
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
//connect to the remove ftp server
client.connect("ftp.worldbestlearningcenter.com");
//log in to the server with user name and password
client.login("yourusername", "yourpassword");
//set the passive mode for the file transfer
client.enterLocalPassiveMode();
//upload file to this directory
client.changeWorkingDirectory("/www");
System.out.println(client.getReplyString());
int reply=client.getReplyCode();
String filename = "d:/SQLiteJava.txt";
fis = new FileInputStream(filename);
if(FTPReply.isPositiveCompletion(reply)){ //connect and login successfully
//upload file to the server
client.storeFile("SQLiteJava.txt", fis);
}
else{
System.out.println("Can't upload to the FTP server.");
}
//log out from the server
client.logout();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (client.isConnected()) {
//disconnect from the server
client.disconnect();
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
If you use Java 7 and Windows 7 or Vista, there is a common problem to transfer the file between the client and the remove FTP server. This problem causes the file transfer failed. You will get the socket exception as shown below.import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class HttpHeaders {
public static void main(String[] args){
ftpUpload();
}
public static void ftpUpload(){
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
//connect to the remove ftp server
client.connect("ftp.worldbestlearningcenter.com");
//log in to the server with user name and password
client.login("yourusername", "yourpassword");
//set the passive mode for the file transfer
client.enterLocalPassiveMode();
//upload file to this directory
client.changeWorkingDirectory("/www");
System.out.println(client.getReplyString());
int reply=client.getReplyCode();
String filename = "d:/SQLiteJava.txt";
fis = new FileInputStream(filename);
if(FTPReply.isPositiveCompletion(reply)){ //connect and login successfully
//upload file to the server
client.storeFile("SQLiteJava.txt", fis);
}
else{
System.out.println("Can't upload to the FTP server.");
}
//log out from the server
client.logout();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (client.isConnected()) {
//disconnect from the server
client.disconnect();
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
To avoid this problem or error, you need to turn off the Windows Firewall (Control Panel-> Windows Firewall). Then run the the Java program again.
|
|
Tuesday, October 8, 2013
Program performance and resources consumption - JConsole
As a software developer, you might want to know the performance of and the resources used by your program so that you can improve it or recommend to the user the CPU speed and size of memory that the user' computer needs to properly run your program.
Java provides a utility called JConsole that can be used to get the information about your program's performance and resources consumption. These information include the number of threads (sub-processes) currently used by the program, the number of deadlock threads (sub-processes hanging), the number of classes loaded and unloaded, the time consumed by the program since it started, the time taken to compile the program, the currently memory size used by the program and the memory size guaranteed available to the program, etc.
To start the JConsole utility for your Java program, you will follow the steps below.
-Run your Java program
-Open the command prompt window and type jconsole
-The Java Monitoring and Management Console displays. Double-click the name of your program or click the Connect button to display the Java Monitoring and Management Console for the program.
If your program is running on the remote machine, you need to select Remote Process instead of the Local Process. Enter the remote host name followed by colon and the port number (hostname:port). You might need to provide the user name and password to connect to the remove host.
On the Monitoring and Management Console interface, there are six tabs-Overview, Memory, Threads, Classes, VM Summary, and MBeas. The Overview tab provides general information about memory usage, threads used, classes loaded and unloaded, and CPU usage.
The Memory tab provides detail information about memory usage. The Threads tab tells you more information about threads run in the program. The Classes tab provides more information about classes loading. The VM Summary shows you the summary information about the Java Visual Machine including process id and name, CUP time, free memory, memory in use, total memory, garbage collection, OS related information, the path of the class file of the program, the path of the libraries to search when loading the libraries, and the boot path used by the bootstrap class loader to search for class files. With MBeans tab you can access the full set of the information including what available and not available in other tabs.
Java provides a utility called JConsole that can be used to get the information about your program's performance and resources consumption. These information include the number of threads (sub-processes) currently used by the program, the number of deadlock threads (sub-processes hanging), the number of classes loaded and unloaded, the time consumed by the program since it started, the time taken to compile the program, the currently memory size used by the program and the memory size guaranteed available to the program, etc.
To start the JConsole utility for your Java program, you will follow the steps below.
-Run your Java program
-Open the command prompt window and type jconsole
-The Java Monitoring and Management Console displays. Double-click the name of your program or click the Connect button to display the Java Monitoring and Management Console for the program.
If your program is running on the remote machine, you need to select Remote Process instead of the Local Process. Enter the remote host name followed by colon and the port number (hostname:port). You might need to provide the user name and password to connect to the remove host.
On the Monitoring and Management Console interface, there are six tabs-Overview, Memory, Threads, Classes, VM Summary, and MBeas. The Overview tab provides general information about memory usage, threads used, classes loaded and unloaded, and CPU usage.
The Memory tab provides detail information about memory usage. The Threads tab tells you more information about threads run in the program. The Classes tab provides more information about classes loading. The VM Summary shows you the summary information about the Java Visual Machine including process id and name, CUP time, free memory, memory in use, total memory, garbage collection, OS related information, the path of the class file of the program, the path of the libraries to search when loading the libraries, and the boot path used by the bootstrap class loader to search for class files. With MBeans tab you can access the full set of the information including what available and not available in other tabs.
Subscribe to:
Comments (Atom)







