A quick script to re-name a file or folder:
Import required:
import java.io.File;
Code:
try{
// File name (or directory) of the file to be renamed
File file = new File(“c:/file1.txt”);
// New File name (or directory)
File file2 = new File(“c:/file2.txt”);
// Rename file (or directory)
file.renameTo(file2);
}catch(Exception e){
e.printStackTrace();
}
Integer to Hexidecimal string:
int intVal = 123;
String hexVal = Integer.toHexString(intVal);
System.out.println(“Hexidecimal: ” + hexVal);
Output:
Hexidecimal: 7b
Hexidecimal string to Integer:
String hexVal = “7b”;
int intVal = Integer.parseInt(hexVal,16);
System.out.println(“Integer: ” + intVal);Output:
Output:
Integer: 123
The following script gets the current directory at runtime:
import java.io.File;
public class CurrentDir {
public static void main (String args[]) {
File dir = new File (“.”);
try {
System.out.println (“Current Directory : ” + dir.getCanonicalPath()); }
catch(Exception e) {
e.printStackTrace();
}
}
}
The same logic can be used to get the parent to the current directory:
import java.io.File;
public class ParentDir {
public static void main (String args[]) {
File dir = new File (“..”);
try {
System.out.println (“Parent Directory : ” + dir.getCanonicalPath());
}
catch(Exception e) {
e.printStackTrace();
}
}
}
This example shows how to use a JOptionPane confirmation dialog with YES / NO Options.
The response is stored in an integer variable which can be used later in the code to perform an action based on the user’s response.
You can change the button labels be changing the options [] values.
Object[] options = { “Yes”,
“No”};
int n =JOptionPane.showOptionDialog(null,
“\n”
+ “Is today Monday?”
+ “\n\n”,
“Please Confirm”,
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[1]);
// YES OPTION CLICKED
if(n == 0){
System.out.println(“YES Clicked”);
}
// NO OPTION CLICKED
if(n == 1){
System.out.println(“NO Clicked”);
}
// CROSS CLICKED
if(n == -1){
System.out.println(“Cross Clicked”);
}
Here is a simple method to calculate seconds since midnight for the current time.
There are a few methods to achieve the same result. This is a quick and easy way.
public getSecondsSinceMidnight() {
DateFormat dateFormat = new SimpleDateFormat();
java.util.Date date = new java.util.Date();
dateFormat = new SimpleDateFormat(“HH”);
date = new java.util.Date();
int hour = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat(“mm”);
date = new java.util.Date();
int minute = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat(“ss”);
date = new java.util.Date();
int second = Integer.parseInt(dateFormat.format(date));
int secondsSinceMidnight = (hour* 3600) + (minute * 60) + second;
System.out.println(“Current Time:” + hour + “:” + minute + “:” + second);
System.out.print(“Seconds Since Midnight: ” + secondsSinceMidnight);
}
Amongst other things, seconds since midnight can be used in calculations to establish accurate differences between 2 times.
The following code illustrates how to derive an age from a given DOB.
This example uses the DOB format YYYY-MM-DD.
This can be altered to any format by changing the substrings taken from the original DOB input.
String dob = “1984-09-20″;
//TAKE SUBSTRINGS OF THE DOB SO SPLIT OUT YEAR, MONTH AND DAY
//INTO SEPERATE VARIABLES
int yearDOB = Integer.parseInt(dob.substring(0, 4));
int monthDOB = Integer.parseInt(dob.substring(5, 7));
int dayDOB = Integer.parseInt(dob.substring(8, 10));
//CALCULATE THE CURRENT YEAR, MONTH AND DAY
//INTO SEPERATE VARIABLES
DateFormat dateFormat = new SimpleDateFormat(“yyyy”);
java.util.Date date = new java.util.Date();
int thisYear = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat(“MM”);
date = new java.util.Date();
int thisMonth = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat(“dd”);
date = new java.util.Date();
int thisDay = Integer.parseInt(dateFormat.format(date));
//CREATE AN AGE VARIABLE TO HOLD THE CALCULATED AGE
//TO START WILL – SET THE AGE EQUEL TO THE CURRENT YEAR MINUS THE YEAR
//OF THE DOB
int age = thisYear – yearDOB;
//IF THE CURRENT MONTH IS LESS THAN THE DOB MONTH
//THEN REDUCE THE DOB BY 1 AS THEY HAVE NOT HAD THEIR
//BIRTHDAY YET THIS YEAR
if(thisMonth < monthDOB){
age = age – 1;
}
//IF THE MONTH IN THE DOB IS EQUEL TO THE CURRENT MONTH
//THEN CHECK THE DAY TO FIND OUT IF THEY HAVE HAD THEIR
//BIRTHDAY YET. IF THE CURRENT DAY IS LESS THAN THE DAY OF THE DOB
//THEN REDUCE THE DOB BY 1 AS THEY HAVE NOT HAD THEIR
//BIRTHDAY YET THIS YEAR
if(thisMonth == monthDOB && thisDay < dayDOB){
age = age – 1;
}
//THE AGE VARIBALE WILL NOW CONTAIN THE CORRECT AGE
//DERIVED FROMTHE GIVEN DOB
System.out.println(age);
This process calculates the current year, month and date to work out if the DOB has already passed this year in order to accuratly establish the age.
This is a simple method for generating a random number between zero (0) and a given number.
The following code example with generate a random number between 0 and 49.
Although the value of maxNumber is set to 50, Java will start the count at 0.
If you want a number between 0 and 50, set the value of maxNymber to 51.
int maxNumber = 50;
int randomNumber = (int)Math.floor(Math.random() * maxNumber);
The following codes assumes that you have created a JScrollPane() called scrollPane
int x = 0;
int y = 10;
scrollPane.getViewport().setViewPosition(new java.awt.Point(x, y));
In this example x sets the horizontal position of a horizontal scroll bar.
y sets the vertical position of a vertical scroll bar – in this case the vertical scroll bar will appear 10 pixels down from the top.
This example shows how to build up a string to post to a web form, and return the results generated.
Element1 is the first variable the the post accepts – “Value 1″ is the literal string bieng passed to it.
Element2 is the second variable that the post accepts – “Value 2″ is the literal string bieng passed to it.
Element3 is the third variable that the post accepts – “Value 2″ is the literal string bieng passed to it.
http://www.examplewebsite.asp is the web page that the data is bieng posted to.
//Create Post String
String data = URLEncoder.encode(“Element1″, “UTF-8″) + “=” + URLEncoder.encode(“Value 1″, “UTF-8″);
data += “&” + URLEncoder.encode(“Element2″, “UTF-8″) + “=” + URLEncoder.encode(“Value 2″, “UTF-8″);
data += “&” + URLEncoder.encode(“Element3″, “UTF-8″) + “=” + URLEncoder.encode(“Value 3″, “UTF-8″);
// Send Data To Page
URL url = new URL(“http://www.examplewebsite.asp”);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get The Response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
//you Can Break The String Down Here
}
You can manipulate the line variable to read in the information returned from the post.
You can force the JTextArea (text area) to scroll to the bottom by moving the caret to the end of the text area after the call to append:
textarea.append(“Some Text\n”);
textarea.setCaretPosition(textarea.getDocument().getLength());