Saturday, February 5, 2011

Directory path for Java applications

It happens that I would like to load or store files with a Java application. Back in the old days, I always wondered how to construct the right relative path. The clue is that all relative pathes are being evaluated from the point of the root directory of the Java application. Considering the whole project as one simple exe file may help to understand this. The basic directions therefore are
  • moving down a directory

    [subdirectory/]subdirectory/file.file-extension

    which is equal to

    ./subdirectory(/subdirectory)file.file-extension
  • moving up a directory

    [../]../file.file-extension

To access a file in a directory on the same level of the application directory, you therefore need to go up a directory to move down into the target directory afterwards.
../target-directory/file.file-extension

Store a text file in Java

When I started coding, I always searched for a simple way to save resluts from a Java application to a simple txt file. These days, I found it on a post-it behind my desk:

First of all, you need a java.io.File instance:
import java.io.File;
// ...
File file = new File („[file-path]file-name.file-extension“);
// ...
And here is the storage method:
import java.io.*;
//...
public static void save(File file) {
    try {

        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.close();
    }
    catch (IOException e) {
        e.printStackTrace();
        System.out.println("Error on file saving.");
    }
}
//...

Searching all files in eclipse

I was always wondering how to search all open projects in eclipse for a particular word. The solution is as simple as that: Somehow copy the word you want to search for in the clipboard an select the torch light in the tool bar and select 2 File Search.