Archive for the 'Java' Category

Search for Files Recursively in Java

In this post, I explained how to find files using wildcard patterns. This current post builds on the code from that post and allows you to do a wildcard search recursively (in all subdirectories) rather than just in a single directory. Notice that this method calls itself (which is what recursiveness is all about).

import java.util.*;
import [...] Read more »

How to Append Text to a File in Java

In a previous post, I wrote about writing text to a new file (or overwriting an existing one). The following code is similar except this time it appends text to the end of an existing one. The path will use the current path where Java is executing unless you specify a directory in filePath (e.g. [...] Read more »

How to Write Text to a File in Java

It is pretty straightforward to write text to a file. This creates a new file (or overwrites an existing one) and writes the text to it that you pass it. The path will use the current path where Java is executing unless you specify a directory in filePath (e.g. C:\\Temp\\JavaTest.txt).

import java.io.*;
 

 
public static void WriteTextToFile(String filePath, [...] Read more »

Force Collections to Accept Only One Data Type in Java

Collections, such as ArrayList and Set, in Java used to be able to contain any class. So you could implement the following code without a problem.

ArrayList oldWay = new ArrayList();
oldWay.Add("xyz");
oldWay.Add(456);
oldWay.Add(new CustomWhatever());

But sometimes this flexibility caused problems because you might want to limit what could be contained in that list (for example, limit it to String [...] Read more »

Read from Multiple Text Files in Java

This post explains a way to read from multiple text files. It builds on this post that explains how to iterate over large files line by line without reading them into memory. It also builds on this post about using wildcards to search for files in a directory.
It also allows you to specify whether the [...] Read more »

Convert an int to a long and Vice Versa in Java

OK, first is to discuss the difference between an int and a long. A long is basically a longer version of an int. Or in other words, it can be bigger or smaller than int and consumes more memory. The following code shows how you can find the maximum values for these. The long class [...] Read more »

How to Compare Two Objects in Java (by Overriding equals)

Here’s a simple class you might use in a Java system:

public class Person
{
public String Name;
public String SocialSecurityNumber;
public String PhoneNumber;
 
public Person(String name, String socialSecurityNumber, String phoneNumber)
{
Name = name;
[...] Read more »

Compare Class Types of Two Objects in Java

If you have two objects and want to determine whether they are instances of the same class, this is easy to do in Java.
Cow c = new Cow();
Print(c instanceof Cow); //true
Print(c instanceof Horse); //false
This also works when you have a class hierarchy (inheritance). The instanceof operator will return true if the object can be “upcast” [...] Read more »

How to GUnzip Files with Java

A common thing to do is to zip files. This combines multiple files into one so it is easier to transport them. It also is helpful because it compresses the files into a smaller size. One utility that is common in Unix/Linux is gzip. The following Java code shows how you would unzip files that [...] Read more »

Find an Object in an ArrayList with Java

Let’s say you have an ArrayList in Java.

ArrayList<String> a = new ArrayList<String>();
a.add("abc");
a.add("def");
a.add("ghi");

Now let’s say you wanted to grab the “def” object out of it. You could do this in the following way:

String b = a.get(a.indexOf("def"));

You can only retrieve an object from an ArrayList by its index. So a simple workaround is first to find the [...] Read more »

Find the Difference Between Two Lists in Java

Let’s say you have two lists in Java that have a lot of overlap between them.

ArrayList a = new ArrayList();
a.add("abc");
a.add("def");
a.add("ghi");
 
ArrayList b = new ArrayList();
b.add("def");
b.add("ghi");
b.add("jkl");

Now let’s say you want to determine what is in b that is not in a. In set theory, you would refer to this as the set-theoretic difference of b in a. [...] Read more »

How to Get Column Names from Database Table with Java

Let’s say you have a table in a SQL database and you want to discover the names of the columns from Java. One way to do this that is pretty straightforward is with the following code.

import java.sql.*;
 

 
public ArrayList<String> GetColumnNames(String tableName) throws Exception
{
DatabaseMetaData meta = _conn.getMetaData();
ResultSet rsColumns = [...] Read more »

Add an Item to an Array in Java

If you haven’t read this post that talks about the differences between arrays and ArrayLists, that would be a good first step. Typically you would use an ArrayList rather than an array if you want to be able to add and remove objects. However, if you would rather (or are required to) use arrays, this [...] Read more »

How to Publish to a WordPress Blog Using XmlRpc

This is the first in a series of posts about how to publish to a WordPress blog using an interface called XmlRpc that is supported by WordPress as well as other blogging platforms.
My motivation for writing these posts is that I have a hobby project that is written in the C# language, and I wanted [...] Read more »

Convert an ArrayList to an Array in Java

OK, back on my soap box; this task is somewhat annoying in Java and should be easier.
If you have an ArrayList object and want to convert it to an array of objects, here’s the way to do it with a minimal amount of code.

ArrayList list = new ArrayList();
list.add("abc");
list.add("def");
list.add("ghi");
 
Object[] array = list.toArray();
 
for (Object x : [...] Read more »

Convert an Array to an ArrayList in Java

Sometimes you have an array but would rather use an ArrayList. This post talks about the differences between these. It’s not super straightforward to do this conversion but not too hard either. Here’s how you would do it for strings.

public static ArrayList<String> CreateStringList(String … values)
{
ArrayList<String> results = new ArrayList<String>();
[...] Read more »

Convert Java List to Delimited String

In this post, I explained how to take a Python list and convert it to a delimited string. It’s a little trickier to do this in Java but not too bad. Below is some code for doing this with either an ArrayList or an array.
Here are the methods:

import java.util.*;
 

 
public static String Join(String[] s, String delimiter)
{
[...] Read more »

What Is the Difference Between Arrays and ArrayLists in Java

This will not be an exhaustive answer. To understand the full details, you’ll need to look at the Java documentation provided by Sun Microsystems.
An array in Java is immutable, which means that when you create it, it is stored in a specific place in memory and never moved until it is no longer needed and [...] Read more »

Add an Array to an ArrayList in Java

No personal offense to the people at Sun, but this has to be one of the most awkward things to do in Java that should not be awkward. You could go about it by looping through the array and adding each element. But this could be expensive if you have a large array or at [...] Read more »

Fast Way to Get All Unique Values from a List in Java

Let’s say you have an ArrayList of string values and want to get all unique values from it. A seemingly obvious way to do this would be to create a list and before adding the next item to check that an identical item doesn’t already exist in the list.

ArrayList uniqueVals = new ArrayList();
 
for (Object x [...] Read more »