Tuesday, January 02, 2007

Transforming to linux-style stream

Why there are differences between the platforms end of line characters? Oh yes, Never ask the WHY question on standarts, so I found my self coding a small block to overcome this mini-crisis:

// given an input stream
final InputStream is = ...;

// create a stream that behaves as a linux-style stream
InputStream linuxStream = new InputStream() {
int previous = -1;
int current = -1;
int next = -1;
  public int read() throws IOException {
if (next != -1) {// a buffered int was readen last iteration
current = next;
next = -1;
} else { // else read an int from the stream
current = is.read();
}
    if (current == 13) {
next = is.read();
if (next == 10) { // encounter "\r\n" transform to "\n"
next = -1;
}
current = 10;
}
return previous = current;
}
}


No comments: