Java Stuff
From TechWiki
Contents |
Basic
Java API Specifications
Terminal Execution
To launch a Java program packaged as ../ch/j-node/project/main/MainGUI.java manually, given the binary files are in a directory .../bin/:
cd /home/jbg/project/bin
java -Djava.library.path=/usr/local/... -classpath .:/usr/local/linux/swt-linux.jar:/usr/local/...:/home/jbg/project/bin/:...
ch.j-node.project.main.MainGUI
Or, alternatively, you can use the JAR file from any directory
java -Djava.library.path=/usr/local/... -classpath .:/usr/local/linux/swt-linux.jar:/usr/local/...:/home/my/path/to/jar/myJar.jar
ch.j-node.project.main.MainGUI
To create a JAR file using Eclipse, see EclipseStuff.
If you just have a jar file:
java -jar /path/to/jar/myJar.jar
Making Life a Little Simpler...
Using bash you can set your .bashrc file to set the correct classpath variables.
In your home directory, edit the file, e.g.,
vim .bashrc
and add
export CLASSPATH=.${CLASSPATH}$(eclipse_to_classpath.sh /home/me/myJava)$(jar_to_classpath.sh /home/me/MyJars/)
The script eclipse_to_classpath.sh gets every Java binary from /home/me/myJava and jar_to_classpath.sh gets the name of every jar file in /home/me/MyJars/. Thanks Markus.
Put the scripts into /usr/local/bin/ or wherever and
source .bashrc
to load changes. To check, type
echo $CLASSPATH
and you should get a list of all your Java related stuff.
Now go to any Java directory
cd /home/me/myJava/someEclipseProject/
Here you should have the foldesr bin/ and, e.g., src/ch/myUrl/Main/ containing your Java classes in the package called ch.myUrl.Main. Next execute
java ch.myUrl.Main.MyMainJavaClass perhapsSomeCongigStuff.xml
where the file perhapsSomeCongigStuff.xml is in the /home/me/myJava/someEclipseProject/ directory.
Code Examples
Arrays of Arrays
An ArrayList of Arrays:
private ArrayList<Double>[] myList;
int lgth = 7;
myList = new ArrayList[lgth];
for (int i = 0; i < lgth; i++)
myList[i] = new ArrayList<Double>();
So myList is an Array of ArrayLists (myList[i]):
myList[ind].add(myDouble); myList[ind].get(i);
To loop through the values of one Arraylist:
for (double val: myList[ind])
There is a problem with generics (unchecked conversion) however, so you need to add the annotation
@SuppressWarnings("unchecked")
in front of the method instantiating the Array, if you want to get rid of the warning.
Histogram
Given an array of data and the value for the granularity (bin size):
double min = min(data);
double max = max(data);
bin = (max - min) / granularity;
Double[] hist = new Double[granularity + 1];
for (int i = 0; i < hist.length; i++) {
hist[i] = 0.0;
}
int offset = -(int) Math.floor(min / bin);
for (int i = 0; i < data.size(); i++) {
int ind = (int) Math.floor(data.get(i) / bin);
if ((ind + offset) <= granularity)
hist[ind + offset] += 1.0;
}
CDF
To get the cumulative distribution from the histogram, use
int size = hist.length;
Double[] cdf = new Double[size];
double sum = 0.0;
int size = hist.length;
double[] sum_i = new double[size];
for (int i = 0; i < size; i++) {
sum += hist[i];
sum_i[i] = sum;
}
for (int i = 0; i < size; i++)
cdf[i] = sum_i[i] / sum * 100;
Clone
Note that
obj a = new Obj(); obj b = a;
results in b beeing (pointing to) the same object as a. Use:
obj b = (obj)a.clone();
if you want a copy of a.
Dates and Times
If you have bizarre problems with using dates, calendars and stuff, try using a different jdk...
Read Milliseconds
Calendar debugCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
debugCal.setTimeInMillis(timeMillis);
System.out.println("time: " + debugCal.getTime());
SimpleDateFormat
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
is 24 h format and
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
is 12 h am/pm format.
Calendar
Date Time = new Date(); Calendar c = Calendar.getInstance(); c.setTime(Time); System.out.println(c.getTime());
Parse
Date t = new Date();
DateFormat df = DateFormat.getInstance();
ObcDateFormat f = new ObcDateFormat("dd.MM.yyy hh:mm:ss");
Date tt = f.parse("12.02.2003 23:55:40");
Conditional
if ( t.before(tt)) {
Get/Set
Set date to now:
Date t = new Date(System.currentTimeMillis());
Get day:
Date t = new Date(); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(t.getTime()); int day = cal.get(Calendar.DAY_OF_WEEK) - 1;
Note that t.getDay() is depricated.
TimeZone
Get time zone info:
TimeZone here = TimeZone.getDefault();
System.out.println(here.getID());
System.out.println(here.getRawOffset()/3600000);
TimeZone.getAvailableIDs();
Calendar.getInstance();
System.getProperty("user.timezone");
Set time zone:
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
ObcDateFormat f = new ObcDateFormat("dd.MM.yyy HH:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("UCT"));
Disable DST
Get Calendar from DateFormat
cal = formatter.getCalendar();
and set
cal.getTimeZone().setRawOffset(0);
Simple I/O
Output to File
PrintStream
Text output to file:
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try
{
// Create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");
// Connect print stream to the output stream
p = new PrintStream( out );
p.println ("This is written to a file");
p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
FileWriter
try {
FileWriter fw = new FileWriter("/mydir/myfile.xyz");
fw.write(myFormatter.format("blablabla\n");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
Format Output
double value;
DecimalFormat myFormatter = new DecimalFormat("#.0000");
fw.write(myFormatter.format(value) + " ");
Read File
Read a file line by line and check for delimiters. This only works since Java 5.0 as it uses the Scanner class.
try {
Scanner s = new Scanner(new File("/myDir/myFile.txt"));
while ( s.hasNextLine() ) {
String str = s.nextLine();
int posDelimiter = str.indexOf(" "); //Delimiter is white space
System.out.println(str.substring(0, posDelimiter));
}
s.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
You can do more fancy delimiting with
new Scanner(...).useDelimiter("...");
A Specific Example
An example using generics, interfaces and inner classes...
Before reading on, have a look at the code in the next section below.
Wrapper.Inner inner = ((Wrapper)(obj.getObject())).new Inner();
here the class Inner, contained in the outer class Wrapper, is instantiated. The syntax is
Wrapper.Inner inner = w.new Inner();
where w is an instance of Wrapper.
The object
Generics<Wrapper> obj;
is an instance of the class Generics:
public class Generics<E extends Interface> {...}
which in this case expects a datatype which extends Interface,i.e., the Wrapper class.
obj.getObject()
will retrieve an object of type Interface from obj. If one wants to extract the implementing class from it, use:
(Wrapper)(obj.getObject())
which returns an instance of Wrapper.
So that is why
Wrapper.Inner inner = ((Wrapper)(obj.getObject())).new Inner();
works.
Code
Main.java
public class Main {
public static void main(String args[]) {
new Main();
}
public Main() {
Generics<Wrapper> obj = new Generics<Wrapper>(new Wrapper());
Wrapper.Inner inner = ((Wrapper)(obj.getObject())).new Inner();
inner.hi();
}
}
Wrapper.java
public class Wrapper implements Interface {
//...
// Inner class
public class Inner {
public final void hi() {
System.out.println("Hello...");
}
}
}
Generics.java
public class Generics<E extends Interface> {
private E obj;
public Generics(E obj) {
this.obj = obj;
}
public final E getObject() {
return obj;
}
}
Interface.java
public interface Interface {
}</nowiki>
