Simple, concise Java examples that do useful things.

Saturday, September 16, 2006

All purpose String trimmer

The java string class supports a trim() operation that trims ' '. You may find that you want to trim another character. This terse example will trim any character from the beginning and end of a String. It is based on the JDK's trim() method with a few more attempts at brevity.



public static String trim(String source, char c) {
int len = source.length();
int st = 0;
char[] val = source.toCharArray();
for (;(st < len) && (val[st] <= c);st++){}
for (;(st < len) && (val[len-1]<=c);len--){}
return ((st > 0) || (len < source.length())) ?
source.substring(st, len) : source;
}

Saturday, September 02, 2006

XMP Dumper reduced

I was able to trim this one down a bit more.


import java.io.*;

public class XMPDumper {

public String getXMP(File f) throws IOException {
return getXMP(new FileInputStream(f));
}

public String getXMP(InputStream is)
throws IOException {
for (int i=0;(i=is.read())!=-1;)
if (i==0xFF && is.read()==0xE1) {
String result = getXMPSegment(is);
if (result.startsWith("http://ns.adobe.com/xap/1.0/"))
return result.substring(29);
}
return null;
}

private String getXMPSegment(InputStream is)
throws IOException {
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[dis.readShort()-2];
dis.read(buffer);
return new String(buffer);
}
}