Archive for the ·

Java

· Category...

Java 8: File handling becomes fun

Comments Off

With the introduction of functional-style syntax and several new Stream based methods in Java 8, file handling finally becomes fun and easy. In fact, the new helper methods and lambda syntax even gives Python a run for its money when it comes to compact code.

Here is how you could read all lines of a file, given as a Path p (since Java 7), and output to stdout.

Files.lines(p).forEach(System.out::println);

To make it a bit more clear what is going on, here a bit more is included and broken up.

Path p = Paths.get("myfile");
 
Stream lines = Files.lines(p);
lines.forEach(System.out::println);
lines.close();

A similarly neat helper function exists for recursively walking over the directory tree of the file system. Again, this prints to stdout.

Files.walk(p).forEach(System.out::println);

Comments Off

Java 7 Released

1 comment

Oracle (finally) released Java 7 today, 4 years and 7 months after the initial release of Java 6. The previous version updates used to be on a 18 months schedule, so that makes this release 37 months late. It’s getting a pretty good bashing on Slashdot, primarily for its current owner, Oracle.

New features includes syntactic sugar like Strings in switch statements; underscores in numeric literals; and type inference for generic instance creation. The Open JDK site lists the same features, so I’m guessing that means everything is open sourced already. However, it seems smaller items on my wish-list did not make it, like the Immutable annotation. (The JSR 305 has been inactive for ages, and still the only implementation is a Google Code hosted project.)

The new Java Doc is here, and latest download from Oracle here. The Open JDK binaries are also available in the repositories of major distributions.

yum install java-1.7.0-openjdk java-1.7.0-openjdk-devel

or
sudo apt-get install openjdk-7-jre openjdk-7-jdk

Java Applet Test

Comments Off

Mostly for my own reference: An old Java Applet which I continue to use to verify that Java Applets works. The applet itself is demonstrating Casteljau’s algorithm to draw a B├ęzier_curve.

You can move the red control points, and then animate the drawing of the curve.

Comments Off

Back references in Java regexp

Comments Off

The Java API documentation for regular expressions says that:

Back references
\n Whatever the nth capturing group matched

This seems to be difficult to get working though. Here’s an example of a work-around:
str.replaceAll(“user(.*)”, “$1″)

Example:
“username” => name

Comments Off