Posts Tagged ‘java’


Dưới đây là các nhóm đã đưa tài nguyên của mình lên web để chia sẻ với lớp:

  1. MoonRaider demo về sử dụng Java
  2. MAL_DB demo về lớp truy uất đa HQTCSDL bằng .Net có thể dễ dàng mở rộng

Java execution error: Exception in thread main java.lang.NoClassDefFoundError

Note that when you run a Java program by calling java, you must put the full classname AT THE END of the command, i.e.
java -cp YourClasspaths YourFullClassname

Lemur ‘s using notes

Use Lemur by Java + Eclipse

Start coding that uses Lemur’s libraries
In eclipse, new a project.
Then go to that project “Build path” (by right click on the project name, choose “Build path…” (or Menu:Project-Properties-Java build path) )
At “Libraries” tab, add the lemur.jar file.

Run written code that uses Lemur’s libraries
At “Order & export” tab, make sure to check the box lemur.jar
Then run it. It should work!

Re-run index note!
If index data destination is already exists, no thing create or the current data is keep, and new data is appended into it!
You should clean up that folder so as new results could be created!

Java tips

Get process id in Java?
Google:java + get process id -> Java Programming [Archive] – Getting Process ID (PID)
There’s no-way pure java. Must use the OS system variable $$.
So when running java program, put a system variable by -DprocessId=$$, then use System.getProperty(“processId”) to get it.


$ cat
public class x {
static void main(String a[]) {
$ javac
$ java -Dpid=$$ x
$ java -Dpid=$$ x
$ ps -p $$ -f
ijbalazs 1844 1842 0 12:02 pts/2 00:00:00 /bin/bash


Read from/write to file in Java?
Google:java + buffered + stream -> Lesson: Basic I/O (The Java™ Tutorials > Essential Classes)

How to convert a Byte[] bytesArray to Long[] longsArray?
Google: java + convert long array to byte array -> Java Programming [Archive] – Cast bytearray into long

byte[] to long[] :

ByteBuffer.wrap(bytesArray).asLongBuffer().get(longsArray) ;

long[] to byte[]:

Read from a text file and Write text to another file?
Google: java write text to file -> Reading and writing text files” href=”″>Java Practices -> Reading and writing text files

Usage context:
Having a text file to read from. Then write the loaded content to another file. How then?

Main idea:
Reading from text file filenameIn, stored in a String content:

File f = new File (filenameIn);
BufferedReader br = (new BufferedReader(new FileReader(f)));
StringBuffer sb = new StringBuffer();
while ( (l=br.readLine())!=null) {
String content = sb.toString();

Writing content to text file filenameOut :

Writer w = new BufferedWriter( new FileWriter(filenameOut) );


How to run external program or command line in Java?
Google: java + compress + object ->Learn Java: Running external commands in Java applications

Main idea :
Use the Runtime.getRuntime.exec(…) function. Below is a sample of usage.


  • Should not use .exec(String) version cause can hardly put in parameters.
  • Can not re-direct standard output using ‘>’ like .exec(“someCommand > outputFile”)
  • Neither can we use piping ‘|’ like .exec(“command1 | command2”)

Sample usage:

//execute cmd ‘command’
String[] cmd = {

, “argument1”,
“argument2”, …
Process p = Runtime.getRuntime().exec(cmd);

//print the output from standard of put of command
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while (true) {
String s = br.readLine() ;
if (s==null) {
break ;
System.out.println(“Exit (code=” + p.exitValue() + “).”);

How to compress/decompress a bytes array? Or even better with an object?
Google: java + compress + object -> Compressing and Decompressing Data using Java

Search for Compressing Object header.

ByteArrayOutputStream baos = new
GZIPOutputStream gz = new GZIPOutputStream(baos);
ObjectOutputStream oos = new
baos.toByteArray(); // this is the compressed data of your objects

Google: java + compress + bytes array
-> Compressing a Byte Array (Java Developers Almanac Example)
-> Decompressing a Byte Array (Java Developers Almanac Example)

How to convert an object to bytes array and convert back from bytes array to object?
(so as to write/read an object stored in a binary file)

To convert an object to bytes array, see the code below from How can I convert any Java Object into byte array? And byte array to file object

public static byte[] getBytes(Object obj) throws{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
byte [] data = bos.toByteArray();
return data;

To convert a byte array back to an object see the code in here Java Programming [Archive] – convert byte array to object

// .. get data into an array named "byteArray"
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(byteArray));
// .. let's say you have a class named "Person"
Person person = (Person) ois.readObject();
// close the input stream (probably not necessary in this case)

Java – binary file – random access?
The tittle is the google search keyword
Source I found:

  1. Physics Simulation and Java – Lecture 9A: Binary File I/O Example
  2. Java I/O skip to the “RandomAccess Files” section.

What u may need as I did:

  • FileInputStream – DataInputStream
    • readInt – writeInt
    • readLong – writeLong
  • RandomAccessFile f
    • seek(0)
    • seek(f.length)
    • getFilePointer //current position of file pointer

How to use an external jar file jarExt in a jar file myJar?
Very easy, you just pay attention when jar-build the myJar file, you add the Class-Path attribute to you manifest file to the location of jarExt as below:
Class-Path: path/to/your/external/jar the/2nd/jar/space/separated
That’s all. Don’t know why Sun mention this in their tutorial not so bold for such a big need like this.

How to compile java source file?
Create your source files, putting them into the folders according to their package (e.g class packageName.any.className must be put in packageName/any/
From your current folder somewhere, compile your code by calling :
javac p2ur.source.files -classpath p2ur.used_packageName.folder -d p2ur.storing.compiledOutput.folder


p2ur is shorthand of
If your code do not using any class other than the ones from the JDK, then forget the classpath argument, which means:

-d p2ur.storing.compiledOutput.folder

If you skip also the -d argument, i.e javac p2ur.source.files , then the output will have the same folder with the source.

Special note:

If your code use other class not in JDK, then without providing classpath the compiler can’t say what the classes you used are! So, you have to tell JDK where those used classes are stored. Remember to give your storing path as the classpath-rule below.

JDK actually try to find those classes in your current folder when no classpath is given. This explains why some other refered-by-your-code classes stored in the same folder with your code will be auto compiled when you compile your code without giving the classpath.
Classpath may contain many paths separated by colon in Linux, semi-colon in Windows.

If your code

How to run java source file?

When you have a .class bytecode file with the main method, you wanna run it? Just call:
java p2ur.bytecode.file
Well, it’s just that simple when your code just used the JDK classes. What if you use the other classes (you wrote yourself, use from others, v.v..) ? Then, JDK will look in the classpath, which default (when not provided) is the current folder where you call java. You add classpath when call java as below.
java -classpath p2ur.bytecode.file
Must notice to the way JDK works with the classpath. If some is need to find, then it will iterate every path, called cpEntry, in classpath and see if cpEntry/any/package/class/name exists.

Note that if you class has package, full package of the class must be called when call java. i.e the whole not only the

Also notice that in the above execution command, classpath must be preceding of the bytecode or it won’t work.

Having the compiled classes, now how to easily distribute?
The answer is to use jar files. The target is to combine a set of classes to a single file. To do this we call :
jar cfm jarOutputFile manifestFile -C classesFolder .
We need to add context for the above command to understand it. Let’s say we have :

  • 2 classes : pack.age1.class1 and pack.age1.class2
    accordingly stored in src/pack/age1/ and src/pack/age2/
    then compiled into bin/pack/age1/class1.class and bin/pack/age2/class2.class
    You may need to look back if you don’t know how to do this.

The above command will create the jar file stored at jarOutputFile which include all the files recuresively stored in the classesFolder. Here, the working folder must be the bin/ folder. You can have this by adding -C path/to/bin  theChosenInBin, where theChosenInBin is the files in bin/ folder to be chosen to add to the jar file. Cause we want to add all files, the command should be -C path/to/bin . (note the dot “.” at the end which means the bin/ folder itself, making JDK auto look for the files inside recursively)

Having the jar file, we can call to run it by :
javar -jar jarOutputFile
but this require a starting point, i.e the main method elsewhere among the classes should be chosen
The main method chosen to be executed is the one indicated in the manifest file as:
Main-class: pack.ageX.classX (enter here)
(end of file here)

, note :
again require the last new-line character ending for the entry, without this the entry won’t be realized by JDK
and we just input  the classname of main class without  .class or .java at the end.

How to print a percentage?

Double perc = Double.valueOf();
System.out.print(String.format(“%1$.2f”, new Object[]{perc})

About classpath
How JDK find your referred classes – the classpath’s rule

Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path. For example, if the package name is

and your class path is


then the compiler and JVM look for .class files in


A class path may include several paths, separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the JVM search the current directory.