Sunday, 30 November 2014

Starting a new Process programmatically from Java

Background

In this post we will see how we can run any process from java programmatically. In specific I will show how can we compile a java file from a Java process. We can very well use Runtime.getRuntime().exec() method to start the process but in this post I am going to demonstrate using ProcessBuilder class.

Code

    public static void executeJavacCommand() throws IOException {

        List<String> paramsExecute = new ArrayList<String>();
        paramsExecute.add("C:\\Program Files\\Java\\jdk1.6.0_31\\bin\\javac.exe");
        paramsExecute.add("-cp");
        paramsExecute.add(".");
        paramsExecute.add("HelloWorld.java");
        ProcessBuilder pBuilder = new ProcessBuilder(paramsExecute);
        Process process = pBuilder.start();
        Reader reader = new InputStreamReader(process.getErrorStream());
        int ch;
        while((ch = reader.read())!= -1)
            System.out.print((char)ch);
        reader.close();

    }

Note1 : In above code I am only printing the error stream of the process but you can manipulate the output stream as well as provide input stream to the process.
Note 2:  You can also see my previous post on how to get the java executable paths. You can programmatically derive those and use it in above code.


Related Links

Finding Java home programatically from Java program

Background

There might be various scenarios in which you might need to get the path of java executable. For example to lets say start java program from withing Java code. In this post we will see how can we achieve that. I will demonstrate a method to find the JAVA_HOME that is usually the JDK directory. Once you have that it is easy to get executable. For eg javac will be in JAVA_HOME/bin/javac.exe

Code

public class JavaHomeTest{

    public static void main(String args[]) throws IOException {
        System.out.println(getJDKDir());
    }

    public static String getJDKDir() {
        File javaHome = new File( System.getProperty( "java.home" ) ).getParentFile();
        File jdkDirectory = null;
        if( javaHome.getName().contains( "jdk" ) ) { 
            //happens in IntelliJ
            jdkDirectory = javaHome;
        } else { 
            //General Scenario - eclipse / command line
            File[] childDirs = javaHome.listFiles();
            for(File file : childDirs) {
                if(file.getName().contains("jdk")) {
                    jdkDirectory = file;
                    break;
                }
            }
            
        }
        return jdkDirectory.getAbsolutePath();
    }

}


Output : 

I am running Windows. The output that I get is 'C:\Program Files (x86)\Java\jdk1.7.0_55'. Code is same for Linux as well. You will get your Java directory.

Saturday, 29 November 2014

How to delete a directory in Java

Background

Well lately I have written a lot of code for file manipulation, I/O etc. So let me take this post to show how can we create or delete directories. Well Java provides APIs for them so it should be pretty straightforward to understand. Important point to look forward is that if you are deleting a directory and it has more files in it then the directory will not get deleted unless all it's children are deleted recursively.  Note File as a Java object can represent either a file or a directory. You can use File 's class isDirectory() method Eg.

        File file = new File("C:\\Users\\athakur\\Downloads");
        if(file.isDirectory()) {
            System.out.println("File is a directory");
        }


Now lets get to creating and deleting directories/files.



Creating a File

To create a file we can use createNewFile() method. Eg - 

        File file = new File("C:\\Users\\athakur\\Downloads\\abc.txt");
        if(!file.exists()) {
            file.createNewFile();
        }

Creating a Directory

To create a directory first create a File object and then call mkdir() on it. Eg -

        File file = new File("C:\\Users\\athakur\\Downloads\\Movies");
        if(!file.exists()) {
            file.mkdir();
        }

Deleting a file/directory

To delete a file or a directory we have to use delete() method. As stated in introductory paragraph if directory has data that data needs to be deleted first. "rm -rf *" does not work in java :).

    public void deleteDirectory(String path) {
        
        File file  = new File(path);
        if(file.isDirectory()){
            String[] childFiles = file.list();
            if(childFiles == null) {
                //Directory is empty. Proceed for deletion
                file.delete();
            }
            else {
                //Directory has other files.
                //Need to delete them first
                for (String childFilePath :  childFiles) {
                    //recursive delete the files
                    deleteDirectory(childFilePath);
                }
            }
            
        }
        else {
            //it is a simple file. Proceed for deletion
            file.delete();
        }
        
    }


Above method will delete complete directory.

Tuesday, 25 November 2014

Install Intellij Idea in Ubuntu

Background

Whichever IDE you use installing it is very easy in Ubuntu. In this post I will show how can we configure Intellij IDEA. Installing Eclipse is also similar. You can see short summary of it in 



Downloading and Installing

  1. Download latest Intellij IDEA from their official site. For me its 'ideaIC-14.0.1.tar.gz'.
  2. Extract the compressed archive to some suitable folder. I will install it in a folder called firefox in my user directory -

    aniket@aniket-Compaq-610:~$ cd firefox/
    aniket@aniket-Compaq-610:~/firefox$ tar xzvf ideaIC-14.0.1.tar.gz
  3. That's pretty much it for downloading and installing part. You can run the IDE by executing idea.sh script file inside the bin folder.

    aniket@aniket-Compaq-610:~/firefox$ cd idea-IC-139.225.3/
    aniket@aniket-Compaq-610:~/firefox/idea-IC-139.225.3$ ./bin/idea.
    sh

Creating launcher for your application

Procedure is same for creating launcher for your executable. I will demonstrate it for IDEA.

aniket@aniket-Compaq-610:~$ cd /usr/share/application/
aniket@aniket-Compaq-610:/usr/share/applications$ sudo gedit idea.desktop


Now add the following lines to it

[Desktop Entry]
Name=IntelliJ IDEA
Comment=IntelliJ IDEA IDE
Exec=/home/aniket/firefox/idea-IC-139.225.3/bin/idea.sh
Icon=/home/aniket/firefox/idea-IC-139.225.3/bin/idea.png
Terminal=false
StartupNotify=true
Type=Application
Categories=Development;IDE;


Above configuration is with respect to my executable path. Change the enteries accordingly. Save the file and run it to launch the application.

Note : Did you notice we put out idea.desktop in '/usr/share/applications' folder. By doing this it will also be accessible from unity search dashboard.



If you remember we had done similar thing for Eclipse. We downloaded the archive file and then created the launcher.

Related Links

Saturday, 22 November 2014

How to install Google chrome on Ubuntu ?

Background

As we all know Firefox is by default the browser that comes with Ubuntu. However there are many users who prefer Chrome over Firefox. So in this post I am going to show how do we do that.


Installing Google Chrome

  • Method 1  : Download package and install
    1. Navigate to https://www.google.com/intl/en-US/chrome/browser/ using any browser  (Eg. Firefox)
    2. You will see download option. Click on it. The download site will automatically detect your operating system and provide download options accordingly.
    3. Select which package you need. Use .deb package for debian based systems and .rmp for fedora and similar distributions. Also choose 32/64 bit based on your system configuration. You can use uname -a command to see the details.

    4. After you download it  use dpkg command to install the package. For fedora you will have to use yum command.

       sudo dpkg -i google-chrome-stable_current_i386.deb

    5. If there are any error simply run

      sudo apt-get -f install

      and re run the command in step 4.

    6.  And chrome should be installed on your system.
  •  Method 2 : For command line Guys/Girls

    1. cd /Downloads
    2. wget https://dl.google.com/linux/direct/google-chrome-stable_current_i386.deb
    3. sudo dpkg -i google-chrome-stable_current_i386.deb
    4. If there are error in step 3 run sudo apt-get -f install and re run step 3.
Note : -f option in apt-get is essentially to fix missing dependencies.

Note : Google chrome is not the same as Chromium browser that you find in Ubuntu repositories (Ubuntu Software center). For starters Chromium is open source while Google chrome is not. For more details you can read the Wiki about Chromium browser. Chromium is the open-source web browser project from which Google Chrome draws its source code.

Related Links

t> UA-39527780-1 back to top