Java

Get the content of a file with Java

by Niklas Waller on May 27, 2010

in Java

Last week I posted some Java code to browse for files on the file system. This week, I will add some code to print the contents of each of the chosen files that was browsed for.

If you look back at the code for browsing for files there was this section where the chosen files were processed. We didn’t do anything but printing the absolute file path to each file.

/* Loop through all files */
for (int i=0;iSystem.out.println(files[i].getAbsoluteFile());
}

I have modified code that I found at Java Tips since it didn’t fully compile and to be a class to call instead of run directly. This code processes a File and stores the content of the file line by line in a string variable which is later returned from the function ‘fileStructure’.

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader; 

public class FileInput {

File file;
FileInputStream fis;
BufferedInputStream bis;
BufferedReader d;
String line;

public FileInput(File inFile) {
file = inFile;
fis = null;
bis = null;
d = null;
line = "";
}

public String fileStructure() {

String retStr = "";

try {
fis = new FileInputStream(file);

bis = new BufferedInputStream(fis);
d = new BufferedReader(new InputStreamReader(bis));

while (line != null) {
line = d.readLine();
if ((line != null)) {
retStr = retStr + '\n' + line;
}
}

fis.close();
bis.close();
d.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return retStr;
}
}

Now we can use this class in the class ‘FileTest’ to print the contents of each browsed file instead of just the file names.

/* Loop through all files */
for (int i=0;i FileInput fi= new FileInput(files[i]);
fileContent = ltrim(rtrim(fi.fileStructure()));
System.out.println(fileContent);
}

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

1 comment

Browse for files with Java Swing

by Niklas Waller on May 20, 2010

in Java

I needed some code to be able to browse for files on the file system with Java so I put together this code that you could use to browse for files on the file system.

You can modify it to only browse files, directories or both:

chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

/*
FILES_ONLY
DIRECTORIES_ONLY
FILES_AND_DIRECTORIES
*/

You can specify which file types (file extensions) you wish to allow the browser to find. In my case I have allowed xml and xsl:

FileFilter filter = new FileNameExtensionFilter("File Extensions","xsl","xml");

The ‘FileTest’ class.
It outputs the chosen file names and their absolute paths on the console.

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

public class FileTest extends JPanel implements ActionListener {
JButton go;
JFileChooser chooser;
String choosertitle;
String fileContent = "";
File[] files;

static final long serialVersionUID = 0;

public FileTest() {
go = new JButton("Browse");
go.addActionListener(this);
add(go);
}

public void actionPerformed(ActionEvent e) {
chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle(choosertitle);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setMultiSelectionEnabled(true);

FileFilter filter = new FileNameExtensionFilter("File Extensions","xsl","xml");
chooser.setFileFilter(filter);

/* Disable the "All files" option */
chooser.setAcceptAllFileFilterUsed(false);

if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
files = chooser.getSelectedFiles();

/* Loop through all files */
for (int i=0;i<files.length;i++) {
System.out.println(files[i].getAbsoluteFile());
}
} else {
System.out.println("No Selection ");
}
}

public Dimension getPreferredSize(){
return new Dimension(200, 100);
}

/* remove leading whitespace */
public static String ltrim(String source) {
return source.replaceAll("^\\s+", "");
}

/* remove trailing whitespace */
public static String rtrim(String source) {
return source.replaceAll("\\s+$", "");
}

public static void main(String s[]) {
JFrame frame = new JFrame("Browse for files");
FileTest panel = new FileTest();
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
}

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

Be the first to comment

Initializing variables in Java and Lotusscript

by Niklas Waller on January 1, 2009

in Java

In Java you have to initialize local variables, that is method variables or else the java file will not compile. Class variables or instance variables don’t have to be initialized on the other hand. In fact it is probably seen as more good-programming to not initialize them.

Here is an example of a function that takes an argument and checks if it is bigger than zero. If so, then set the local variable ‘returnValue’ to that value plus 5. The code below won’t compile. The error message ‘The local variable returnValue may not have been initialized’ is raised.
The reason for this is that returnValue may not get a value (num could be less than 1). Since it is not initialized during declaration to a default value either, the code will not compile.

public int returnNumber(int num) {
int returnValue;

if (num > 0) {
returnValue = num + 5;
}

return returnValue;
}

Now, if we were talking about an instance variable, a class variable, this would not be a problem since these variables are initialized by default. Primitives get their default values like 0 and 0.0 for integers and floating numbers and references are set to null. So we could do something like this without a problem. Notice that it is the same code but that the variable returnValue is an instance variable instead.

public class InitializeTest {

private int returnValue;

public int returnNumber(int num) {

if (num > 0) {
returnValue = num + 5;
}

return returnValue;
}
}

Something that could be a bit confusing to programmers that only uses lotusscript is this difference since they are used to not having to initialize variables at all, i.e. lotussript behaves with variables like Java class variables all the time. Indeed you won’t have to declare variables either unless you specifically specify ‘Option Declare’ in the Options section of a script library or agent. Good or bad? You decide. I like the Java approach better.

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

1 comment

Query an SQL-database from Java

by Niklas Waller on September 23, 2008

in Java

I have done this many times with PHP and ASP and also with Lotusscript. But I haven’t had the reason yet to try it with Java. It turned out to be very straight forward there as well and similar as the other languages.

On my machine I have installed MySQL Community Server, the MySQL ODBC Connector and the GUI tools for the MySQL Query browser. The installation and configuration is very straight forward.
When the installations and the standard configuration are done you can create a simple database with a table, a few fields and some example rows.

Then create a User DSN in the ODBC Data Source Administrator for this database with the MySQL ODBC Driver. I have named this one ‘dbTest’.

Now you are ready to write the code.
We have two static methods below, one for getting data using the sql SELECT command and one static method for inserting data using the sql INSERT COMMAND. Simply uncomment the call to the function you would like to use and modify the querystring which are located in these methods to best fit your purposes. Sorry about the indentation.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class Database {
static String userid = “”;
static String password = “”;
static String url = “jdbc:odbc:dbTest”;

static Connection con = null;

public static void main(String[] args) throws Exception {
Connection con = getOracleJDBCConnection();
if(con != null){
getData();
//insertData();
} else {
System.out.println(“Could not Get Connection”);
}

con.close();
}

public static void getData() {
String query = “SELECT * FROM customers”;

try {
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();

// Print all rows and columns
while (rs.next()) {
for (int i=1; i<=rsmd.getColumnCount(); i++) {
System.out.print(rs.getString(i) + ” “);
}
}

statement.close();
} catch(SQLException ex) {
System.err.println(“SQLException: ” + ex.getMessage());
}
}

public static void insertData() {
String query = “INSERT INTO customers (name, numEmployees) VALUES (‘Company E’, 500000)”;

try {
Statement statement = con.createStatement();
statement.executeUpdate(query);
statement.close();
} catch (SQLException ex) {
System.err.println(“SQLException: ” + ex.getMessage());
}
}

public static Connection getOracleJDBCConnection(){

try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

} catch(java.lang.ClassNotFoundException e) {
System.err.print(“ClassNotFoundException: “);
System.err.println(e.getMessage());
}

try {
con = DriverManager.getConnection(url, userid, password);
} catch(SQLException ex) {
System.err.println(“SQLException: ” + ex.getMessage());
}

return con;
}
}

Execution returns:

Since this worked and if you would like to query some other database like Oracle or something else, you have to make sure there is a DSN setup for it on the machine where the code runs and everything else should work the same way.

JDBC tutorial.com is a good tutorial. I got some parts of the code form here to get started.

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

1 comment

The basics of Java constructors

by Niklas Waller on June 12, 2008

in Java

Everytime you create an object in Java one or several so-called constructors are called. You can say that they are used to initialize the object. It is the first thing that runs when the object is created and every class must have one. Well not entirely true, actually all the instance varables are assigned default values first.

A constructor looks a bit like a method but it isn’t. It must not have a return type and it must have the same name as the class. It is invoked by the keyword “new”. Here is a simple class with a constructor:

public class Wohill {
public Wohill() {
System.out.println(“This is the constructor”);
}
public status void main(String[] args) {
Wohill wo = new Wohill();
}
}

A new object of class ‘Wohill’ is created in the main function and on this creation the constructor is called. When running it prints “This is the constructor”.

It is also possible to leave out the constructor. And if you do, the compiler will create one for you (the default constructor). In this case it will be a no-arg constructor. If you however provide a constructor on your own, a no-arg or a var-arg constructor you are on you own. A class can hereby stated have one or several constructors. Having several is called having overloaded constructors. So you can implement constructors with the same name as above but with different argument lists. The reason for this is that there might be requirements to create an object with predefined values of different kinds or just a default one. However there can not be two constructors with the same argument list.

Below you can see several contructors implemented legally:

public class Wohill {
// Instance variables
private int width;
private String name;

// A no-arg constructor
public Wohill() {
width=0;
name=”default”;
}

// A var-arg constructor
public Wohill(String aName, int aWidth) {
name = aName;
width = aWidth;
}

// Another var-arg constructor
public Wohill(int aWidth, String aName) {
name = aName;
width = aWidth;
}

// And another var-arg constructor
public Wohill(String name) {
this.name = name;
}
}

As mentioned shortly above several constructors can be called on an object creation. This is the case when using inheritance, i.e. if your class has a superclass. Class ‘Wohill’ below is the subclass of its superclass ‘Blog’. Class ‘Blog’s superclass is class ‘Object’ which is the superclass of all classes.

public class Blog {
public Blog() {
System.out.println(“Blog constructor”);
}
}

public class Wohill extends Blog {
public Wohill() {
System.out.println(“Wohill constructor”);
}
}

When creating a Wohill object its constructor runs. The first thing that happens in the Wohill constructor is that its superclass constructor is called and so on. When we have reached the top constructor in the inheritance tree that constructor runs and after that the constructor that called it and so on until the Wohill constructor finally runs. This is called ‘constructor chaining’ and in this case it produces the output:
Blog constructor
Wohill constructor

Some more facts:
- Constructors can use any access modifier.
- Interfaces do not have constructors
- A constructor can only be invoked from another constructor
- A superclass’ constructor can be called explicitly user the keyword ‘super’ with or without arguments depending on the superclass constructor(s),

There are more information about this and again I would like to recommend the books “Head First Java” and “Sun Certified Programmer for Java 5 – Study Guide” by Kathy Sierra and Bert Bates from which I have been inspired and learned a lot about Java.

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

2 comments

Keyword functions in Java for Domino

by Niklas Waller on June 10, 2008

in Java

When working with Lotus Notes Domino as a developer you often use so-called keywords documents to get values to use in the code. The purpose of this is is to NOT hard code any settings and to give the users the ability to change these values easily without asking developers to enter the code and start making changes.
A keyword document often consists of a keyword-value pair and a view is used to lookup a keyword to get the actual value. Sometimes one keyword is used to get several values but in this case it is easier to get the document as a return value instead of a string and then get values from that document after a lookup.

Here are three different functions made in Java to get keywords in a Notes environment. These functions belong to a class of course and you have to include the lotus.domino.* package to get it to work. Nowadays I code Java for Domino only in Eclipse since it’s a so much better development client.

Function 1 – getKeyword:

/**
* Get keyword value from keyword view based on a keyword.
*
* @param viewKeywords The keywords view.
* @param keyword The keyword used to get the wanted value.
* @param keywordFieldValue The name of the value field in the keyword document.
* @return value The value that is held by keyword.
* @author Niklas Waller
* @version 2008-06-04
*/
public String getKeyword(View viewKeywords, String keyword, String keywordFieldValue) {
String returnKeyword = “”;

try {
Document docKeyword = viewKeywords.getDocumentByKey(keyword);

if (docKeyword != null) {
returnKeyword = docKeyword.getItemValueString(keywordFieldValue);
} else {
returnKeyword = “”;
}

} catch(Exception e) {
// You could also log to a log database here
e.printStackTrace();
}

return returnKeyword;
}

Function 2 – getKeywordValues:

/**
* Get keyword value from keyword view based on a collection keyword and an actual keyword. The view has to be constructed in a specific way so that the first column is categorized and with a collection value. The second column is the keyword and the third the value for the keyword for the collection.
*
* @param keyword1 Keyword that describes the collection of keywords in view ‘keywords’.
* @param keyword2 The actual keyword with which the value is fetched.
* @return keyword string
* @author Niklas Waller
* @version 2007-10-12
*/
private String getKeywordValues(String keyword1, String keyword2) {

String retval = “”;

try {
View view = db.getView(“keywords”);
ViewEntryCollection vec = view.getAllEntriesByKey(keyword1);

ViewEntry ve = vec.getFirstEntry();

while (ve != null) {
Vector v = ve.getColumnValues();

if (keyword2.compareTo((String)v.elementAt(2)) == 0) {
retval = String.valueOf(v.elementAt(3));
}
ve = vec.getNextEntry(ve);
}

} catch(Exception e) {
// You could also log to a log database here
e.printStackTrace();
}

return retval;
}

Function 3 – getKeywordDocument:

/**
* Get a specific keyword document based on a keyword value.
*
* @param viewKeywords The keywords view.
* @param keyword The keyword used to get the wanted value.
* @return docKeyword The keyword document.
* @author Niklas Waller
* @version 2008-06-09
*/
public Document getKeywordDocument(View viewKeywords, String keyword) {
Document docKeyword = null;

try {
docKeyword = viewKeywords.getDocumentByKey(keyword);
} catch(Exception e) {
// You could also log to a log database here
e.printStackTrace();
}

return docKeyword;
}

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

Be the first to comment

The Java switch statement

by Niklas Waller on May 29, 2008

in Java

The general form of a switch statement looks like this:

switch (expression) {
case const1: code
case const2: code
case const3: code
default: code
}

The expression:

- A switch’s expression must evaluate to values that can implicitly cast to an int – in other words char, byte, short, int and enum. This means it can be a call to a function as long as the function return the right value.
- It can only check for equality, that is not greater than or less than or something like that.
- Boxing is allowed. See example 1.1.

Cases:

- Case constants are evaluated from top and down. The first case that matches the expression is the entry point in the switch clause. After entering, execution will continue for each subsequent case statement unless there is a break (see below).
- The case constant (for example const1 above), must evaluate to the same type as the switch expression can use and it has to be a compile-time constant (see below).
- There can not be more than one label using the same value. See example 1.2 which is illegal.
- The special case “default” can be used for the cases when there are no match.

The break statement:

The keyword “break” can be inserted at the end of each code block for each case statement, After entering some case statement that code block will run. If it ends with a “break”, execution will immediately move out of the switch block. If there is no “break”, execution will continue for each case statement until a break is found or until the end of the switch clause, this is referred to as fall-through. See example 1.3 for a simple example that uses “break”.

Compile-time constant:

The definition from Sun is:

A compile-time constant expression is an expression denoting a value of primitive type or null or a String that is composed using only the following:

Literals of primitive type, null and literals of type String

So for the case of a switch clause, the compile-time constant is an int or a type that can be implicitly cast to an int and that can be resolved at compile time, which means that a case constant can only be a constant or a final variable that is assigned a literal int value.

Example 1.1:

switch (new Integer(2)) {
case 2: System.out.println(“This works!”);
}

Example 1.2:

switch (x) {
case 2: System.out.println(“2″);
case 2: System.out.println(“2″);
case 3: System.out.println(“3″);
default: System.out.println(“default”);
}

Example 1.3:

switch (x) {
case 1:
System.out.println(“1″); break;
case 2:
System.out.println(“2″); break;
case 3:
System.out.println(“3″); break;
default:
System.out.println(“default”); break;
}

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

Be the first to comment

Preparing for SCJP 5

by Randolph Guy on May 20, 2008

in Java

I am and have been preparing for the Sun Certified Java Programmer 5 exam for 1,5 years now. The preparation has been mostly theoretical but also quite some non-theoretical practice like different examples and exercises. I have also written a few Lotus Notes Java agents in my daily work as a Lotus Notes and Domino developer and administrator. I am still very glad that I took this decision and my plans are to complete the certification at the latest in october this year (2008).

I would like to state that I know the Java syntax pretty good now. I need some more practical training and assignments to be really good and familiar with it but that will come with time and experience.

When I decided to go for it I put up a small plan to follow and that was to read two books and to get as much practical training as possible during this time,

The first book to start with that I really recommend is called Head First Java. It is very popular and has gotten many good reviews. You should be somewhat familiar with programming though to get the most out of it. Preview the book at Google books.

The second book that is very good as well is called SCJP Sun Certified programmer for Java 5 Study Guide. This book covers it all that you need to know to pass the exam. It is required that you really understand the language but you will get some extra hints here as well. Preview the book at Google books. Both books are written by Kathy Sierra and Bert Bates which has written numerous of other good technical litterature.

I will finish this book at the end of the summer and then test exams will take over the reading. Together with the SCJP book comes lots of practice exam questions and besides this there are many sites to visit to get more.

I will put up a Java reference page as well later on for those of you that might be interested. Who knows, some of the future projects of Wohill might come in Java flavour.

Share and Enjoy:

  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • email
  • Google Buzz
  • RSS
  • Slashdot
  • Technorati
  • Add to favorites
  • DZone
  • LinkedIn
  • MySpace
  • Tumblr

Be the first to comment