Posts in the “java” category

Java Timestamp example: How to create a “current timestamp” (i.e., now)

Java date/time FAQ: When working with the Timestamp class, how do I create a “Java current timestamp”? For instance, how do I create a JDBC Timestamp object to represent the “current time” (“now”)?

Solution

You can create a “current time” JDBC Timestamp in just a few lines of code, using the Java Calendar class and a java.util.Date instance, as shown in this example code:

[toc hidden:1]

How to get tomorrow’s date in Java

Java Date FAQ: How do I determine tomorrow's date in Java?

Many times when you're working with a Java Date, you need to be able to add something to a date, i.e., to get tomorrow's date, or the next week, or the next year. In this short tutorial, we'll demonstrate how to easily add one day to today to get tomorrow's date.

Java Date FAQ: How do I get today’s date?

Java Date FAQ: Can you show me how to get today's date in Java?

Getting a Java Date object that represents "today" or "now" is fairly simple. The following sample code shows how to do this:

Date date = Calendar.getInstance().getTime();

If you haven't worked with the Java Date class before, I should point out that I'm referring to a java.util.Date class here, and not a java.sql.Date class. To make this a little more clear, I could write that same code like this:

How to open and read a text file in Java (FileReader, BufferedReader)

Java File I/O FAQ: How do I open a file and read text from it using Java? (Also written as, “How do I use the Java BufferedReader and FileReader classes to read from a text file?”)

Solution: Here’s a method taken from a Java class I wrote that shows how to open and read a file using the Java FileReader class. This uses the most recent Java syntax and classes.

Java open and read file example

In the following Java method, the file is opened with the Java FileReader and BufferedReader, and then, as each line of the file is read it is assigned to a Java String, with each String in turn being added to an ArrayList named records.

/**
 * Open and read a file, and return the lines in the file as a list
 * of Strings.
 * (Demonstrates Java FileReader, BufferedReader, and Java5.)
 */
private List<String> readFile(String filename)
{
  List<String> records = new ArrayList<String>();
  try
  {
    BufferedReader reader = new BufferedReader(new FileReader(filename));
    String line;
    while ((line = reader.readLine()) != null)
    {
      records.add(line);
    }
    reader.close();
    return records;
  }
  catch (Exception e)
  {
    System.err.format("Exception occurred trying to read '%s'.", filename);
    e.printStackTrace();
    return null;
  }
}

Note that when I read and open the file, I just catch any errors that may occur with a generic Exception object, but if you need to handle more specific problems you can catch the individual IOException and FileNotFoundException objects.

(As a side note, if you're interested in formatting your text output, note that I use System.err.format to print my error output.)

Opening a text file with Java

As you can see from the example, I open the text file using this line of code:

BufferedReader reader = new BufferedReader(new FileReader(filename));

You want to use both a BufferedReader and FileReader like this when reading from a text file in Java. I don't know why a FileReader doesn't handle buffering, but it doesn't, so you add the BufferedReader to make it much faster to read larger files. The BufferedReader also gives you the convenient readLine method. For more information about this, see my Java FileReader examples/tutorial and my Java BufferedReader examples.

You can also use some methods of the Java File class to test that the file exists and is readable, but I've skipped those steps in this example, as those problems will be caught with the try/catch statement.

Java file read and open example - Summary

I hope this Java file-open and file-read example has been helpful. If you have any questions, just leave a note in the Comments section.

A Java class that writes to and reads from a remote socket

I'm not going to describe this much today, but here's the source code for a Java class I put together from a number of other sources on the internet. In short, this code uses a Java Socket to connect to a port on a remote server, sends a command to that server to be executed, and then reads the output from the command that is executed. As a result, I assume that all information sent is text (nothing binary).

How do I convert a String to a long with Java?

Question: How do I convert a String to a long with Java?

Answer: The Long class includes a method named parseLong() that serves just this purpose. An example of a simple program that performs this conversion is shown below:

Java ‘int’ array examples (declaring, initializing, populating)

Java array FAQ: How do you create an array of Java int values (i.e., a Java “int array”)?

Answer: There are several ways to define an int array in Java; let’s take a look at a few examples.

1) Declare a Java int array with initial size; populate it later

If you know the desired size of your array, an you'll be adding elements to your array some time later in your code, you can define a Java int array using this syntax:

Java: How to find the longest String in an array of Strings

Java String array FAQ: Can you share an example of how to determine the largest String in a Java String array?

Sure, in this tutorial I'll share the source code for a complete Java class with a method that demonstrates how to find the longest String in a Java string array.

Finding the longest string in a Java string array

Here's the source code that shows how to find the longest string in a Java String array:

Java String array examples (with Java 5 for loop syntax)

Java String array FAQ: Can you share some Java array examples, specifically some String array examples, as well as the Java 5 for loop syntax?

Sure. In this tutorial, we'll show how to declare, populate, and iterate through a String array, including the Java 5 for loop syntax. Because creating a String array is just like creating and using any other Java object array, these examples can also work as more generic object array examples.

[toc hidden:1]

A Java keytool certificate example: Using ‘keytool’ with certificate files

Java keytool FAQ: Can you share an example of how to use the Java keytool command to create and share a Java/keytool certificate?

Here's a quick look at how two people, John and Paul, might use the Java keytool command to create and share a certificate file. In this example, John will create the certificate with the "keytool genkey" and "keytool export" commands, and Paul will import John's public key from the certificate file with the "keytool import" command.

Java 5 for loop syntax example (Java 5 Generics)

Java FAQ: Can you show me an example of the Java 5 for loop syntax? (Java 5 and newer)

Answer: Sure. I've created a sample Java program to demonstrate the Java 5 for-each loop syntax, using both a List with pre-Java5 syntax, and a second example using Java 5 generics syntax.

Java 5 for loop syntax example

Without any further ado, here is the example code:

How to control Java heap size (memory) allocation (xmx, xms)

Java memory FAQ: How do I control the amount of memory my Java program uses (i.e., Java RAM usage)?

One of the Linux servers that I use is a little starved for memory, but I need to run a Java program on it periodically to run some utility tasks. However, every time I try to run the program I get this Java heap size error message:

[toc hidden:1]

Java and FTP: A Java class that lists FTP return codes (status codes)

I was just digging around through a Java FTP program I wrote, and found the following class, which might be a nice reference for other people. This class lists all the possible FTP server return codes (status codes) that your Java FTP program can receive in return to a call to an FTP server.