Java not found or wrong java version - update-alternatives on Linux environment


Hola!

OK so let's rock... here are the possible problems:
0. No java / javac found.
1. Somehow you have two or more java (JRE or/and JDK) installed on the system.
2. Setting JAVA_HOME to your preferred version does not help as some stuff still use system default version
3. Cannot find javac or java even if JAVA_HOME set.


Strange but can happen if more than one version installed.

Time for some fixes:
Let say your preferred JAVA_HOME is pointing to /home/user/jdk

For setting JAVA_HOME and PATH please refer to the post:
Setting JAVA_HOME environment variable

System alternatives and updates

1. Install some java alternatives:
sudo update-alternatives --install /usr/bin/java java /home/user/jdk/bin/java 1
sudo update-alternatives --install /usr/bin/javac javac /home/user/jdk/bin/javac 1
sudo update-alternatives --install /usr/bin/javac javaws /home/user/jdk/bin/javaws 1

2. Set / notify the system:
sudo update-alternatives --set java /home/user/jdk/bin/java
sudo update-alternatives --set javac /home/user/jdk/bin/javac
sudo update-alternatives --set javaws /home/user/jdk/bin/javaws

3. Set the preferred one if have more alternatives
sudo update-alternatives --config java
sudo update-alternatives --config javac
sudo update-alternatives --config javaws


This is it! You should be up an running with your old new great JAVA world :)


Java - how to parse and format date

Hello,

This is about another common scenario when it comes to parse a date from a String or other way - format a text to a date.

Java has some build-in classes that can help in java.text package which are:
  • SimpleDateFormat
  • DateFormat
Parsing date from text:
String dateString = "22/10/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse(dateString);

Format text to date:
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String dateString = sdf.format(date);

Constructor take one argument for actual date format type which can also include time. For example: dd/MM/yyyy, dd-MM-yyyy, yyyy-MM-dd HH:mm

For full documentation visit official java docs page.

Using the JDK versions could be enough for single-threaded environments. However it's not always the best way to parse or format dates. For example it's not thread safe and also it's not always the fastest way.

Luckily there are very good alternatives:
  • FastDateFormat from Apache Commons - thread-safe and fast but only formatting is supported (sorry no parsing from a String)
  • DateTimeFormat from Joda - thread safe and immutable support both parsing and formatting
API for both are pretty simple and intuitive but for more specific details see related documentation.

I would recommend using Joda instead of JDK version or if you need only formatting the best would be FastDateFormat.

Cheers!


Object serialization and deserialization in Java

Hola!

Java provides an API for nice and simple mechanism of serializing and deserializing objects.

In order to serialize an object it has to implement Serializable interface, e.g.

public class Person implements Serializable {
     
    private static final long serialVersionUID = 1L; //  kind of version that must be the same if you want to deseriazlie object later

...
}

Also note the serialVersionUID has been defined. This is important to match that this is the same object type when it will come to de-serialization. In simple words it used to verify if the objects are compatible.

That's all with the pre-requirements So next you want to serialize Person object. Here is kind of generic method which can do the job:

public static final void serialize(Object object, String filename) {
    try {
        FileOutputStream f_out = new FileOutputStream(new File(filename));
        ObjectOutputStream obj_out = new ObjectOutputStream(f_out);
        obj_out.writeObject(object);
        obj_out.close();
    } catch (Exception e) {
        // log error with serialization
    }

}

Basically you can call it for any serializable object, e.g.
serialize(person, "person.dat"); // serialize single person object
seriazlie(persons, "persons.dat"); // serialize collection of persons

In order to deserialize object from file you can use following bit of code:
public static final Object deserialize(String filename) {
    try {
        FileInputStream f_in = new FileInputStream(new File(filename));
        ObjectInputStream obj_in = new ObjectInputStream(f_in);
        Object object = obj_in.readObject();
        obj_in.close();
        return object;
    } catch (Exception e) {
         
    }
    return null;
}



For example:
Person person = deserialize("person.dat");


That should do the job.



How to access Windows registry from Java?

Hi,

Many desktop applications may require access to the Windows registry in order to store or retrieve some data. For example it can be an application in trial version that needs to store installation date and time or expired date.

The Java Development Kit (JDK) contains required code to do it. It's available in WindowsPreferences class from java.util.prefs package. However the code is declared as private which makes it invisible.

The "magic" trick is to use reflecation API to access private methods. I will not include code directly here because it would pretty long copy-paste and I am too lazy for that.

Instead please refer to Real's HowTo at the following link:
Real's HowTo - accessing windows registry


That's it! Have check it myself and it works like a charm :)

Cheers!

Java: quick way to read or write to file

Hi there,

Reading and writing to files in Java is very common use case. Sometimes you may not remember how to do it quickly and often need to search for it on google.

So here it is...

For file writing here comes FileWriter Java class. You can use constructor which takes either File or String as an argument. For example let say you want to create/write to a file named test.txt:

FileWriter writer = new FileWriter("test.txt"); // creates or overrides existing file
// or FileWriter writer = new FileWriter( new File("test.txt") );

writer.append("blah blah blah"); // append some text to the file
writer.append("\n"); // new line

// and at the end
writer.flush(); // flush the stream
writer.close();


Simple as that - file has been saved to your current working directory.

Now it's FileReader who reads data from files. For example:
FileReader fileReader = new FileReader(new File("test.txt"));

// now you may want to read line by line so here comes BufferedReader

BufferedReader br = new BufferedReader(fileReader);

String line = null;
// if no more lines the readLine() returns null
while ((line = br.readLine()) != null) {
     // reading lines until the end of the file

}

That's it. Simple stuff but worth of having it here to find quickly.

Cheers :)

Java: how to get website source code as a String

Hi all,

Getting a website source code can be useful in many programs esepcially when it come to getting and/or parsing some third party data. This can be achive very easy in Java. Few steps to note:
1. Open URL connection based on www address.
2. Using reader to read the input.
3. StringBuilder can be used to store the data.
4. Close the stream.

Above in java can look like the following code:
public static String getPageSource(String urlstr) {
  StringBuilder sb = new StringBuilder();
  try {
    URL url = new URL(urlstr);
    URLConnection yc = url.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
      sb.append(inputLine);
    }
    in.close();

    return sb.toString();
  } catch (Exception e) {
    // log / throw exception depending what you want
  }


  return null;
}


Cheers :)

JAVA: how to open URL in a browser programatically?

Hi there,

It's been a while since last post but here we go again :)

OK so sometimes you may want to open internet website from within your java application. It may sound complicated but in the end it's very simple.

If program is running on Windows OS you can do it by using default system program (browser) associated with the given file type, try using following code:

String url = "http://www.google.com/"; // example www
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);


For other system you may want to find which browser are present and ready for action:

String[] browsers = { "firefox", "opera", "mozilla", "netscape" }; // common browser names
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++)
  if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0)
    browser = browsers[count]; // have found a browser

Runtime.getRuntime().exec(new String[] { browser, url }) // open using a browser


This is it :)