Posts Tagged Java

JTextFileParser 1.4

I’ve just released a small update to JTexFileParser adding the ability to export text file data to XML.
Check it out at google code.

JTexFileParser is a java package built for simplifing delimited text files parsing. It gives you a quick way for parsing a delimited text file, managing rows and row’s fields.

Scriptlet and JSTL variable sharing

I know that mixing scriplets and JSTL in JSP is a bad practice, but sometimes you can’t avoid it and every time I do it I can’t remember how to share variables between scriplets and JSTL so this post is a sort of reminder for the future. Hope it can be useful for other forgetful persons like me :-)

Access scriptlet variable with JSTL

<%
String myVariable = "Test";
pageContext.setAttribute("myVariable", myVariable);
%>
<c:out value="myVariable"/>

Access JSTL variable with scriptlet

<c:set var="myVariable" value="Test"/>
<%
String myVariable = (String)pageContext.getAttribute("myVariable");
out.print(myVariable);
%>

When Runtime.exec() won’t – JavaWorld

A well written article on JavaWorld that explains how to effectively use the Runtime.exec() method. It really saved me a lot of time.

When Runtime.exec() won’t – JavaWorld

Writing text files using Java

This simple method shows hot to write to text files using Java.
If the file exists it will append the new text to it, otherwise it creates a new file. This is achieved using the FileWriter class and its constructor:

public FileWriter(String fileName, boolean append) throws IOException

Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written. JavaDoc.

public void writeToFile(String text, String filePath){
 
  try {
 
    File thisFile = new File(filePath);
 
    BufferedWriter writer = new BufferedWriter(
                                new FileWriter(filePath, thisFile.exists()));
    writer.write( text );
    writer.newLine();
 
    writer.flush();
    writer.close();
 
  } catch (IOException e) {
    e.printStackTrace();
  }
}

Java tail

A java implementation of the Unix tail command. This is a small customization of the java tail class created by Luigi Viggiano. I’ve just added some controls and added the update time parameter.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
/**
 * Java implementation of the Unix tail command
 * 
 * @param args[0] File name
 * @param args[1] Update time (seconds). Optional. Default value is 1 second
 * 
 * @author Luigi Viggiano (original author) http://it.newinstance.it/2005/11/19/listening-changes-on-a-text-file-unix-tail-implementation-with-java/
 * @author Alessandro Melandri (modified by)
 * */
public class Tail {
 
  static long sleepTime = 1000;
 
  public static void main(String[] args) throws IOException {
 
    if (args.length > 0){
 
      if (args.length > 1)
        sleepTime = Long.parseLong(args[1]) * 1000;
 
      BufferedReader input = new BufferedReader(new FileReader(args[0]));
      String currentLine = null;
 
      while (true) {
 
        if ((currentLine = input.readLine()) != null) {
          System.out.println(currentLine);
          continue;
        }
 
        try {
          Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
          break;
        }
 
      }
      input.close();
 
    } else {
      System.out.println("Missing parameter!\nUsage: java JavaTail fileName [updateTime (Seconds. default to 1 second)]");
    }
  }
}

Install Sun JDK on Linux

I’ve tested this procedure on Fedora 10 and Ubuntu 9.04 but It should work on other distributions too.

First of all download the latest JDK package from the SUN page: be sure to download the bin file and not the rpm.

From now on you’ll need to run commands using ”sudo”.

Move the package to /opt/ and make it executable.

cd /path/to/download/folder
mv jdk-versionnumber-linux-i586.bin /opt/
cd /opt/
chmod +x jdk-versionnumber-linux-i586.bin

Now start the installation and follow the onscreen instructions

./jdk-versionnumber-linux-i586.bin

When the installation is done you’ll need to set the JAVA_HOME enviroment variable and add java executable to the system pah.

Open the file /etc/profile and add the following lines

JAVA_HOME="/opt/jdk_versionnumber"
export JAVA_HOME
 
PATH=$PATH:/opt/jdk_versionnumber/bin/
 
export PATH

Now add a symbolic link for the java command

ln -s /opt/jdk_versionnumber/bin/java /usr/bin/java

Log off and log in back and you’re done.

Get the WEB-INF folder path

This is a simple example on how to get the WEB-INF directory path in a J2EE web application.

public class MyClassName{
 
  private static final String WEBINF = "WEB-INF";
 
  public String getWebInfPath(){
 
    String filePath = "";
 
    URL url = MyClassName.class.getResource("MyClassName.class");
    String className = url.getFile();
 
    filePath = className.substring(0,className.indexOf(WEBINF) + WEBINF.length());
    return filePath;
  }
 
}

Connect to MySql using Java

This is a simple class that I usually use to connect to a MySQL database. Obviously the right MySQL JDBC driver must be in your classpath.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class ConnectionManager {
 
    // Connection data -- START
 
    static final String driver   = "com.mysql.jdbc.my_driver_version";
    static final String dbserver = "mysql.server.name";
    static final String dbport   = "mysql.database.port";
    static final String dbname   = "mysql.database.name";
    static final String dbuser   = "mysql.database.username";
    static final String dbpass   = "mysql.database.password";
 
    // Connection data -- END
 
    /**
     * Opens a connection to the database
     *
     * @return Returns a Connection object
     */
    public static Connection getConnection(){
 
        Connection con = null;
 
        try {
 
            Class.forName(driver).newInstance();
            String conString = "jdbc:mysql://"+dbserver+":"+dbport+"/"+dbname;
            con = DriverManager.getConnection(conString,dbuser, dbpass);
 
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
 
        return con;
    }
 
    public static void close(Object object){
 
        if (object != null){
 
            try {
 
                if (object instanceof Connection)
                    ((Connection)object).close();
 
                else if (object instanceof Statement)
                    ((Statement)object).close();
 
                else if (object instanceof PreparedStatement)
                    ((PreparedStatement)object).close();
 
                else if (object instanceof ResultSet)
                    ((ResultSet)object).close();
 
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                object = null;
            }
        }
    }
}