Java Pgms
Java Pgms
This example shows you how to add weeks to a date. package net.javaiq.examples.date; import java.util.Calendar; import java.util.GregorianCalendar;
/** * This class demonstrates on how to add weeks to a date. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class AddWeeksToDate { /** * Adds the required number of weeks to the date */ public static java.sql.Date addWeeks(final java.util.Date date, final int weeks) { java.sql.Date derivedDate = null; if (date != null) { final GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(Calendar.DATE, weeks * 7); derivedDate = new java.sql.Date(calendar.getTime().getTime()); } return derivedDate; } /** * Tests add weeks to a date method with sample inputs * @param args */ public static void main(String[] args) { final java.util.Date currentDate = new java.util.Date(System.currentTimeMillis()); System.out.println("Current Date : " + currentDate); final int weeksToAdd = 10; final java.sql.Date calculatedDate = addWeeks(currentDate, weeksToAdd); System.out.println("Date after adding weeks : " + calculatedDate); } }
/** * This class demonstrates on how to add months to a date * @author JavaIQ.net * Creation Date Dec 3, 2010 */ public class AddMonthsToDate { /**
* Adds the required number of months to the date */ public static java.sql.Date addMonths(final java.util.Date date, final int months) { java.sql.Date calculatedDate = null; if (date != null) { final GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(Calendar.MONTH, months); calculatedDate = new java.sql.Date(calendar.getTime().getTime()); } return calculatedDate; }
/** * Tests add months to a date method with sample inputs * @param args */ public static void main(String[] args) { final java.util.Date currentDate = new java.util.Date(System.currentTimeMillis()); System.out.println("Current Date : " + currentDate); final int monthsToAdd = 5; final java.sql.Date calculatedDate = addMonths(currentDate, monthsToAdd); System.out.println("Date after adding months : " + calculatedDate); } }
/** * This class demonstrates on how to add years to a date * @author JavaIQ.net * Creation Date Dec 3, 2010 */ public class AddYearsToDate { /** * Adds the specified number of years to the given date */ public static java.sql.Date addYears(final java.util.Date date, final int years) { java.sql.Date calculatedDate = null; if (date != null) { final GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(Calendar.YEAR, years); calculatedDate = new java.sql.Date(calendar.getTime().getTime()); } return calculatedDate; }
/** * Tests add years to a date method with sample inputs * @param args */ public static void main(String[] args) { final java.util.Date currentDate = new java.util.Date(System.currentTimeMillis()); System.out.println("Current Date : " + currentDate); //Note: the input is a negative number, hence substracts the num of years from the input date final int yearsToAdd = -5; final java.sql.Date calculatedDate = addYears(currentDate, yearsToAdd); System.out.println("Date after adding years : " + calculatedDate); } }
*/ public class BeforeDateChecker { /** * checks if the given date is before today */ public static boolean beforeToday(final java.util.Date date) { boolean isBeforeToday = false; if (date != null) { final java.util.Date today = new java.util.Date(); isBeforeToday = date.before(today); } return isBeforeToday; }
/** * Tests before today method with sample inputs * @param args */ public static void main(String[] args) { final java.util.Date inputDate = new java.util.Date(System.currentTimeMillis()); System.out.println("Input Date : " + inputDate); final boolean isInputDateBeforeToday = beforeToday(inputDate); System.out.println("isInputDateBeforeToday : " + isInputDateBeforeToday); } }
/** * This class demonstrates on how to format a date * @author JavaIQ.net * Creation Date Dec 3, 2010 */ public class DateFormatter { private static char separator = '/'; private static String[] validDateFormats = new String[] { "DDMMYYYY", "MMDDYYYY", "YYYYMMDD", "YYYYDDMM", "MMYYYY", "YYYYM M", "MMMYYYY", "DD", "MMDDYY", "DDMMYY", "YYMMDD" };
/** * Returns the string representation in the corresponding format. * Valid date formats valid are DDMMYYYY, MMDDYYYY, YYYYMMDD, YYYYDDMM, MMYYYY, YYY YMM, MMMYYYY, DD,
* MMDDYY, YYMMDD, DDMMYY * @param date * @param format * @param dateSeparator * @return */ public static String format(Date date, String format, char dateSeparator) { String formattedDate = null; if (date != null) { String allowed = " -./"; String dateSeparatorString = String.valueOf(separator); if (allowed.indexOf(dateSeparator) >= 0) { dateSeparatorString = String.valueOf(dateSeparator); } else if (dateSeparator == '\u0000') { dateSeparatorString = ""; } if (format.trim().equalsIgnoreCase("DDMMYYYY")) { formattedDate = formatDate(date, "dd" + dateSeparatorString + "MM" + dateSeparatorString + " yyyy"); } else if (format.trim().equalsIgnoreCase("MMDDYYYY")) { formattedDate = formatDate(date, "MM" + dateSeparatorString + "dd" + dateSeparatorString + " yyyy"); } else if (format.trim().equalsIgnoreCase("YYYYDDMM")) { formattedDate = formatDate(date, "yyyy" + dateSeparatorString + "dd" + dateSeparatorString + "MM"); } else if (format.trim().equalsIgnoreCase("YYYYMMDD")) { formattedDate = formatDate(date, "yyyy" + dateSeparatorString + "MM" + dateSeparatorString + "dd"); } else if (format.trim().equalsIgnoreCase("MMYYYY")) { formattedDate = formatDate(date, "MM" + dateSeparatorString + "yyyy"); } else if (format.trim().equalsIgnoreCase("YYYYMM")) { formattedDate = formatDate(date, "yyyy" + dateSeparatorString + "MM"); } else if (format.trim().equalsIgnoreCase("DD")) { formattedDate = formatDate(date, "dd"); } else if (format.trim().equalsIgnoreCase("MMMYYYY")) { formattedDate = formatDate(date, "MMM" + dateSeparatorString + "yyyy"); } else if (format.trim().equalsIgnoreCase("DDMMYY")) { formattedDate = formatDate(date, "dd" + dateSeparatorString + "MM" + dateSeparatorString + " yy"); } else if (format.trim().equalsIgnoreCase("MMDDYY")) { formattedDate = formatDate(date, "MM" + dateSeparatorString + "dd" + dateSeparatorString + " yy"); } else if (format.trim().equalsIgnoreCase("YYMMDD")) { formattedDate = formatDate(date, "yy" + dateSeparatorString + "MM" + dateSeparatorString + " dd"); } } return formattedDate; }
/** * Formats the given date in the specified format
* @param date * @param format * @return formattedDate */ public static String format(Date date, String format) { return format(date, format, separator); }
/** * Formats the given date in the specified format without the separator * @param date * @param format * @return formattedDate */ public static String format(Date date, String format, boolean separatorRequired) { if (separatorRequired) { return format(date, format); } else { return format(date, format, '\u0000'); } } /** * Formats the given date in the specified format * @param date * @param format * @return formattedDate */ private static String formatDate(java.util.Date date, String format) { SimpleDateFormat df = new SimpleDateFormat(format); return df.format(date) + ""; } /** * Fetches the valid date formats * @return validDateFormats */ public static String[] getAvailableDateFormats() { return validDateFormats; } /** * Tests date formatting methods with sample inputs * @param args */ public static void main(String[] args) { final java.sql.Date inputDate = new java.sql.Date(System.currentTimeMillis()); System.out.println("Input Date : " + inputDate); String formattedDate = format(inputDate, "DDMMYYYY"); System.out.println("Formatted date : " + formattedDate); formattedDate = format(inputDate, "DDMMYYYY", false); System.out.println("Formatted date with no separator : " + formattedDate);
} } 7. How do I find day of the week for any given This example shows you how to find day of the week for any given date. package net.javaiq.examples.date; /** * This class demonstrates on how to find day of the week for any given date. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class DayOfTheWeekFinder { /** * This method returns the Day Of Week */ public static double findDayOfTheWeek(int day, int month, int year) { double a = Math.floor((14 - month) / 12); double y = year - a; double m = month + 12 * a - 2; double d = (day + y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) + Math.floor((31 * m) / 12)) % 7; return d + 1; } /** * Method to test the methods in the class with sample inputs * @param args */ public static void main(String[] args) { //Here we want to find what day of the week it was on 15th July 1976 System.out.println(findDayOfTheWeek(15, 7, 1976)); } }
date?
/** * This class demonstrates on how to calculate days between 2 given dates * @author JavaIQ.net * Creation Date Dec 3, 2010 */ public class DaysBetweenCalculator { /** * Calculates the total number of days between the two given dates */ public static int getDaysBetween(java.util.Date date1, java.util.Date date2) { if (date1 == null || date2 == null) {
return -1; } GregorianCalendar gc1 = new GregorianCalendar(); gc1.setTime(date1); GregorianCalendar gc2 = new GregorianCalendar(); gc2.setTime(date2);
if (gc1.get(Calendar.YEAR) == gc2.get(Calendar.YEAR)) { return Math.abs(gc1.get(Calendar.DAY_OF_YEAR) - gc2.get(Calendar.DAY_OF_YEAR)); } long time1 = date1.getTime(); long time2 = date2.getTime(); long days = (time1 - time2) / (1000 * 60 * 60 * 24); return Math.abs((int)days); } }
} earliestDate = date.before(earliestDate) ? date : earliestDate; } } } return earliestDate; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { EarliestDateFinder earliestDateFinder = new EarliestDateFinder(); } }
/** * This class demonstrates on how to find the latest date for a given set of dates. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class LatestDateFinder { public LatestDateFinder() { } public static Date findLatestDate(Date date1, Date date2) { Date latestDate = null; if (date1 != null && date2 != null) { latestDate = date1.getTime() > date2.getTime() ? date1 : date2; } return latestDate; } public static Date findLatestDate(Date[] dates) { Date latestDate = null; if ((dates != null) && (dates.length > 0)) { for (Date date: dates) { if (date != null) { if (latestDate == null) { latestDate = date; } latestDate = date.after(latestDate) ? date : latestDate; } } } return latestDate; }
/** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { } }
/** * This class demonstrates on how to check if a year is a leap year * @author JavaIQ.net * Creation Date Dec 3, 2010 */ public class LeapYearChecker { /** * Returns whether it is a leap year or not */ public static boolean isLeapYear(int year) { GregorianCalendar gc = new GregorianCalendar(); return gc.isLeapYear(year); } /** * Tests leap year checker method with sample inputs * @param args */ public static void main(String[] args) { int year = 2076; final boolean isLeapYear = isLeapYear(year); if (isLeapYear) { System.out.println(year + " is a leap year."); } else { System.out.println(year + " is not a leap year."); } } }
/** * This class demonstrates on how to find end date of any given month in a year * @author JavaIQ.net
* Creation Date Dec 3, 2010 */ public class MonthEndDateCalculator { /** * calculates the last date of a month */ public static java.sql.Date calculateMonthEndDate(int month, int year) { int[] daysInAMonth = { 29, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int day = daysInAMonth[month]; boolean isLeapYear = new GregorianCalendar().isLeapYear(year); if (isLeapYear && month == 2) { day++; } GregorianCalendar gc = new GregorianCalendar(year, month - 1, day); java.sql.Date monthEndDate = new java.sql.Date(gc.getTime().getTime()); return monthEndDate; } /** * Tests month end date calculation method with sample inputs * @param args */ public static void main(String[] args) { int month = 2; int year = 2076; final java.sql.Date calculatedDate = calculateMonthEndDate(month, year); System.out.println("Calculated month end date : " + calculatedDate); } }
firstCal.setTime(firstDate); Calendar secondCal = Calendar.getInstance(); secondCal.setTime(secondDate); isEqual = firstCal.get(Calendar.YEAR) == secondCal.get(Calendar.YEAR) && firstCal.get(Calendar.MONTH) == secondCal.get(Calendar.MONTH); } return isEqual; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) throws Exception { Date firstDate = new SimpleDateFormat("MM-dd-yyyy").parse("12-10-2010"); Date secondDate = new SimpleDateFormat("MM-dd-yyyy").parse("12-18-2010"); boolean isEqual = checkIfMonthAndYearAreEqual(firstDate, secondDate); if (isEqual) { System.out.println("Month and year of the passed dates are equal."); } else { System.out.println("Month and year of the passed dates are not equal."); } secondDate = new SimpleDateFormat("MM-dd-yyyy").parse("12-18-2011"); isEqual = checkIfMonthAndYearAreEqual(firstDate, secondDate); if (isEqual) { System.out.println("Month and year of the passed dates are equal."); } else { System.out.println("Month and year of the passed dates are not equal."); } } }
return (nth - 1) * 7 + 1 + (7 + weekDay - findDayOfTheWeek((nth - 1) * 7 + 1, month, year)) % 7; int days = 0; if (leapYear(year)) { days = daysOfMonthLeapYear[month - 1]; } else { days = daysOfMonth[month - 1]; } return (days - (findDayOfTheWeek(days, month, year) - weekDay + 7) % 7); } /** * This method returns true if the given year is Leap Year */ public static boolean leapYear(int year) { if ((year / 4) != Math.floor(year / 4)) return false; if ((year / 100) != Math.floor(year / 100)) return true; if ((year / 400) != Math.floor(year / 400)) return false; return true; } /** * This method returns the Day Of the Week */ public static double findDayOfTheWeek(int day, int month, int year) { double a = Math.floor((14 - month) / 12); double y = year - a; double m = month + 12 * a - 2; double d = (day + y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) + Math.floor((31 * m) / 12)) % 7; return d + 1; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { //Here we want to find when the second saturday falls in the month of July 2020 int nth = 2; // indicating to find second occurence int weekDay = 7; // indicates to find saturday. Note sunday value is 0 and saturday value is 7 int month = 7; // indicates july month int year = 2020; // obvious! // The day of the month on which second saturday occurs in July 2020 double nthDay = findNthWeekDayOfTheMonth(nth, weekDay, month, year); System.out.println(" The day of the month : " + nthDay); } }
/** * This class demonstrates on how to convert String date to a Calendar. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class StringDateToCalendarConverter { public static Calendar convertStringDateToCalender(String strDate) { Calendar cal = null; if (strDate != null) { try { DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy"); Date date = formatter.parse(strDate); cal = Calendar.getInstance(); cal.setTime(date); } catch (Exception e) { e.printStackTrace(); } } return cal; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { String date = "12-10-2010"; Calendar calender = convertStringDateToCalender(date); System.out.println("Converted Calendar : " + calender); } }
How do I format time to AM/PM. This example shows you how to format time to AM/PM.
package net.javaiq.examples.date; import java.sql.Time; /** * This class demonstrates on how to format time to AM/PM. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class TimeFormatter { /** * Method to change the given time in to AM PM format like hh:mm:ss AM */ public static String getFormattedTime(Time inputTime) { String formattedTime = ""; if (inputTime != null) { java.util.StringTokenizer st = new java.util.StringTokenizer(String.valueOf(inputTime), ":"); int hrs = Integer.parseInt((String)st.nextToken()); String mins = st.nextToken(); String secs = st.nextToken();
String meridian = ""; if (hrs > 12) { hrs = hrs - 12; meridian = "PM"; } else if (hrs == 12) { meridian = "PM"; } else { meridian = "AM"; } formattedTime = hrs + ":" + mins + ":" + secs + " " + meridian; } return formattedTime; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { Time currentTime = new Time(System.currentTimeMillis()); System.out.println("currentTime :: " + currentTime); String formattedTime = getFormattedTime(currentTime); System.out.println("formattedTime :: " + formattedTime); } }
/** * This class demonstrates on how to copy/extend/increase an existing array to accomodate * new elements * @author JavaIQ.net * Creation Date Oct 11, 2010 */ public class ArrayExtender { /** * Demonstrates copying elements from one array to another */ public void demonstrateArrayCopy() { //initial array with 3 employees String[] employees = new String[] { "Chris", "Kara", "Amanda" }; //Create the extended array to accomodate 2 more employees String[] extendedEmployees = new String[5]; //Add more names to the extended array extendedEmployees[3] = "Francis"; extendedEmployees[4] = "Ian"; //System class has arraycopy method which copies elements from one array to another
//arraycopy(Object src, int srcPos,Object dest, int destPos, int length); System.arraycopy(employees, 0, extendedEmployees, 0, employees.length); // Printing the contents of the array to console for (int i = 0; i < extendedEmployees.length; i++) { System.out.println(extendedEmployees[i]); } } /** * Tests array copy method * @param args - command line arguments */ public static void main(String[] args) { // Create arrayExtender object ArrayExtender arrayExtender = new ArrayExtender(); // calling the method which shows how to copy arrays elements in Java arrayExtender.demonstrateArrayCopy(); } }
How do I find the count the number of a particular value object in a collection?
This example shows you how to find the count the number of a particular value object in a collection. package net.javaiq.examples.collections; import java.util.ArrayList; import java.util.Collection; import java.util.List;
/** * This class demonstrates on how to find the count the number of a particular * value object in a collection * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class CollectionValueObjectSizeFinder { /** * Method to count the number of value objects in a given collection * @param coll -- the Collection to find the values. * @param val -- the value to compare each of the elements to. * @return size -- the number of value objects in the passed Collection */ public static int getNumberOfValueObjectsInCollection(Collection<Object> coll, Object val) { int numOfValueObjectsInColl = 0; if (coll != null) { for (Object collObj: coll) { if (collObj != null) { if (collObj.equals(val)) numOfValueObjectsInColl++; } else { if (val == null) numOfValueObjectsInColl++; } }
} return numOfValueObjectsInColl; } /** * Tests getNumberOfValueObjectsInCollection method with sample inputs * @param args */ public static void main(String[] args) { List list = new ArrayList(); list.add("Google"); list.add("Yahoo"); list.add("Bing"); list.add("Google"); int num = getNumberOfValueObjectsInCollection(list, "Google"); System.out.println("Value object count in the collection :: " + num); } }
/** * This class demonstrates on how to convert a tokenized string to an array * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class StringToArrayConverter { /** * Method to convert a tokenized string to a string array * @param tokenizedString -- the tokenized string which needs to be converted * @param token -- the token which separates the values in the input string. * @return stringArray -- the converted string array */ public static String[] convertTokenizedStringToStringArray(String tokenizedString, String token) { String stringArray[] = null; if ((tokenizedString != null) && (token != null)) { StringTokenizer st = new StringTokenizer(tokenizedString, token); int i = 0; stringArray = new String[st.countTokens()]; while (st.hasMoreElements()) { stringArray[i] = st.nextToken(); i++; } } return stringArray; } /** * Method to convert a tokenized string to an int array
* @param tokenizedString -- the tokenized string which needs to be converted * @param token -- the token which separates the values in the input string. * @return stringArray -- the converted int array */ public static int[] convertTokenizedStringToIntArray(String tokenizedString, String token) { int intArray[] = null; if ((tokenizedString != null) && (token != null)) { StringTokenizer st = new StringTokenizer(tokenizedString, token); int i = 0; intArray = new int[st.countTokens()]; while (st.hasMoreElements()) { intArray[i] = Integer.parseInt(st.nextToken()); i++; } } return intArray; } /** * Method to test the methods in the class with sample inputs * @param args */ public static void main(String[] args) { String token = ","; String stringCsv = "Red,Green,Blue"; String[] convertedStringArray = convertTokenizedStringToStringArray(stringCsv, token); for (String str: convertedStringArray) { System.out.println(str); }
String intCsv = "007,786,555,143"; int[] convertedIntArray = convertTokenizedStringToIntArray(intCsv, token); for (int num: convertedIntArray) { System.out.println(num); } } }
/** * This class demonstrates on how to convert a tokenized string to an array list * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class StringToArrayListConverter {
/** * Method to convert a tokenized string to an array list of string type * @param tokenizedString -- the tokenized string which needs to be converted * @param token -- the token which separates the values in the input string. * @return list -- the converted string array list */ public static ArrayList<String> convertTokenizedStringToList(String tokenizedString, String token) { ArrayList<String> list = null; if ((tokenizedString != null) && (token != null)) { StringTokenizer st = new StringTokenizer(tokenizedString, token); list = new ArrayList<String>(); while (st.hasMoreElements()) { list.add(st.nextToken()); } } return list; } /** * Method to test the methods in the class with sample inputs * @param args */ public static void main(String[] args) { // Comma separated values String csv = "Red,Green,Blue"; String token = ","; ArrayList<String> list = convertTokenizedStringToList(csv, token); for (String item: list) { System.out.println(item); } } }
/** * This class demonstrates on how to convert a tokenized string to an array list * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class EmailValidator { /** * This method validates if a given email Id is a valid email address. * @param emailId -- The EmailId which needs to be validated * @return isEmailIdValid -- true if email address is valid, false otherwise. */ public static boolean isEmailIdValid(String emailId) { boolean isEmailIdValid = false; if (emailId != null && emailId.length() > 0) {
String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(emailId); if (matcher.matches()) { isEmailIdValid = true; } } return isEmailIdValid; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { } }
} /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { System.out.println("1. Phone Number is " + isPhoneNumberValid("123-456-7890")); System.out.println("2. Phone Number is " + isPhoneNumberValid("(234) 456-7890")); System.out.println("3. Phone Number is " + isPhoneNumberValid("1234567890")); System.out.println("4. Phone Number is " + isPhoneNumberValid("234567-789")); } }
/** * This class demonstrates on how to validate a SSN (Social Security Number) in Java * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class SsnValidator { /** isSSNValid: Validate Social Security number (SSN) using Java reg ex. * This method checks if the input string is a valid SSN. * @param ssn String. Social Security number to validate * @return boolean: true if social security number is valid, false otherwise. */ public static boolean isSsnValid(String ssn) { boolean isValid = false; /*SSN format xxx-xx-xxxx, xxxxxxxxx, xxx-xxxxxx; xxxxx-xxxx: ^\\d{3}: Starts with three numeric digits. [- ]?: Followed by an optional "-" \\d{2}: Two numeric digits after the optional "-" [- ]?: May contain an optional second "-" character. \\d{4}: ends with four numeric digits. Examples: 879-89-8989; 869878789 etc. */ //Initialize reg ex for SSN. </CODECOMMENTS> String expression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$"; CharSequence inputStr = ssn; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(inputStr); if (matcher.matches()) { isValid = true; } return isValid; }
/** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { System.out.println("1. SSN is " + isSsnValid("234-56-7890")); System.out.println("2. SSN is " + isSsnValid("234-56-78900")); System.out.println("3. SSN is " + isSsnValid("234567890")); System.out.println("4. SSN is " + isSsnValid("234567-789")); } }
package net.javaiq.examples.string; import java.util.StringTokenizer; /** * This class demonstrates on how to convert a tokenized string to an array * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class StringToArrayConverter { /** * This method converts a tokenized string into a string array using string tokenizer class * @param str : String -- the tokenized string which needs to be converted * @param token : String -- the token which separates the strings * @return strArr : String[] -- converted String array */ public static String[] getArrayFromTokenizedStringOldWay(String str, String token) { String strArr[] = null; if (str != null && token != null) { StringTokenizer st = new StringTokenizer(str.trim(), token.trim()); int i = 0; strArr = new String[st.countTokens()]; while (st.hasMoreElements()) { strArr[i] = st.nextToken(); i++; } } return strArr; } /** * This method converts a tokenized string into a string array using the split method in String class * @param str : String -- the tokenized string which needs to be converted * @param token : String -- the token which separates the strings * @return strArr : String[] -- converted String array */ public static String[] getArrayFromTokenizedString(String str, String token) { String strArr[] = null; if (str != null && token != null) { strArr = str.split(token); } return strArr; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { String tokenizedString = "Clinton,Bush,Obama"; String[] strArr = getArrayFromTokenizedStringOldWay(tokenizedString, ","); for (String str: strArr) { System.out.println(str); } strArr = getArrayFromTokenizedString(tokenizedString, ",");
* This has been tested only windows but can be adapted for *nix * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class DateBasedDirectoryCreator { public static String createDateBasedDirectory(String baseDirectory, Date argDate) { String newDir = null; if (baseDirectory != null && argDate != null) { try { String format = "yyyy-MM-dd"; DateFormat dateFormatter = new SimpleDateFormat(format); String date = dateFormatter.format(argDate); File f = new File(baseDirectory); File files[] = f.listFiles(); String dir = null; int baseDirLength = baseDirectory.length(); int checkingLength = baseDirLength + format.length() + 3; int maxSeqNo = 0; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { dir = files[i].toString(); if (dir.length() == checkingLength) { String existingDirDate = dir.substring(baseDirLength, baseDirLength + 10); if (date.equalsIgnoreCase(existingDirDate)) { int dirSeqNo = Integer.parseInt(dir.substring(baseDirLength + 11, baseDirLength + 10 + 3)); if (dirSeqNo > maxSeqNo) { maxSeqNo = dirSeqNo; } } } } } String currSeq = "" + (maxSeqNo + 1); if (currSeq.length() == 1) { currSeq = "0" + currSeq; } newDir = baseDirectory + date + "-" + currSeq; new File(newDir).mkdir(); } catch (Exception e) { e.printStackTrace(); } } return newDir; } /** * Method to test other methods in the class with sample inputs * In this example 2 directories are created for current date and 1 directory for a previous date. * Make sure the base directory in the file system with proper access. * @param args */ public static void main(String[] args) throws ParseException { Date currentDate = new java.util.Date(System.currentTimeMillis());
String baseDir = "C:/Admin/Backup/"; String newDir = createDateBasedDirectory(baseDir, currentDate); System.out.println("New Directory 1 :: " + newDir); newDir = createDateBasedDirectory(baseDir, currentDate); System.out.println("New Directory 2 :: " + newDir); Date oldDate = new SimpleDateFormat("yyyy-MM-dd").parse("2010-12-09"); newDir = createDateBasedDirectory(baseDir, oldDate); System.out.println("New Directory 3:: " + newDir); } }
public void searchFile(String dirName, String fileName) { File f = new File(dirName); File files[] = f.listFiles(); for (int i = 0; (i < files.length) && !fileFound; i++) { if (files[i].isDirectory()) { String newDir = dirName + fileSeparator + files[i].getName(); searchFile(newDir, fileName); } else { if (files[i].getName().equalsIgnoreCase(fileName)) { filePath = files[i].getAbsolutePath(); lastModifiedDate = new java.util.Date(files[i].lastModified()).toString(); fileFound = true; break; } } } } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { FileSearcher fileFinder = new FileSearcher(); String fileName = "FileUtility.java"; String searchDirectory = "D:\\APPS\\eRASU"; fileFinder.searchFile(searchDirectory, fileName);
if (fileFinder.fileFound) { System.out.println("File Name : " + fileName); System.out.println("File Directory : " + fileFinder.filePath); System.out.println("Last Modified Date : " + fileFinder.lastModifiedDate); } else { System.out.println("File " + fileName + " not found in " + searchDirectory + " or in any of its sub-folders."); } } }
inputStream = new FileInputStream("C:\\Sample.txt"); String streamText = convertInputStreamToText(inputStream); System.out.println(streamText); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
} }
package net.javaiq.examples.math;
/** * This class demonstrates on how to generate a range of tokenized numeric values. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class RangeValuesGenerator { /** * @param low : Double -- the starting number * @param high : Double -- the ending number * @param token : String -- the token which separates the numbers * @return tokenizedRange : String -- the generated range */ public static String generateRangeValuesAsString(Double low, Double high, String token) { StringBuffer tokenizedRange = new StringBuffer(""); if (low != null && high != null && token != null && high > low) { for (; low <= high; low++) { tokenizedRange.append(low); if (low != high) { tokenizedRange.append(token); } } } return tokenizedRange.toString(); } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { String rangeValuesCsv = generateRangeValuesAsString(1.0, 7.0, ","); System.out.println(rangeValuesCsv); } }
String driver = "oracle.jdbc.driver.OracleDriver"; // The driver class (classes12.jar) should be in the classpath String userName = "Test"; String password = "test@123"; Connection con = null; try { Class.forName(driver); con = DriverManager.getConnection(url, userName, password); } catch (Exception e) { e.printStackTrace(); } return con; } /** * Method to test the methods in the class with sample inputs * @param args */ public static void main(String[] args) { getConnectionForOracleDatabase(); } }
/** * This class demonstrates on how to execute a external command from Java. * For example how to execute a batch file from Java or a shell script from Java. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class ExternalCommandExecutor { public static String executeExternalCommand(String[] cmdArray) { StringBuffer commandOutput = new StringBuffer(""); try { Process process = Runtime.getRuntime().exec(cmdArray); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = input.readLine()) != null) { commandOutput.append(line); commandOutput.append("\n"); } } catch (Exception e) { e.printStackTrace(); } return commandOutput.toString(); } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) {
String[] cmdArray = new String[1]; cmdArray[0] = "C:\\test.bat"; String commandResult = executeExternalCommand(cmdArray); System.out.println("Command Result :: " + commandResult); } }