File Format DOS/Unix/MAC code sample

Posted by mac on Stack Overflow See other posts from Stack Overflow or by mac
Published on 2010-06-18T00:31:50Z Indexed on 2010/06/18 0:43 UTC
Read the original article Hit count: 518

Filed under:
|
|

I have written the following method to detemine whether file in question is formatted with DOS/ MAC, or UNIX line endings.

I see at least 1 obvious issue: 1. i am hoping that i will get the EOL on the first run, say within first 1000 bytes. This may or may not happen.

I ask you to review this and suggest improvements which will lead to hardening the code and making it more generic.

THANK YOU.

new FileFormat().discover(fileName, 0, 1000);

and then

public void discover(String fileName, int offset, int depth) throws IOException {

    BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName));
    FileReader a = new FileReader(new File(fileName));

    byte[] bytes = new byte[(int) depth];
    in.read(bytes, offset, depth);

    a.close();
    in.close();
    int thisByte;
    int nextByte;

    boolean isDos = false;
    boolean isUnix = false;
    boolean isMac = false;

    for (int i = 0; i < (bytes.length - 1); i++) {
        thisByte = bytes[i];
        nextByte = bytes[i + 1];
    if (thisByte == 10 && nextByte != 13) {
            isDos = true;
            break;
        } else if (thisByte == 13) {
            isUnix = true;
            break;
        } else if (thisByte == 10) {
            isMac = true;
            break;
        }
    }
    if (!(isDos || isMac || isUnix)) {
            discover(fileName, offset + depth, depth + 1000);
    } else {
        // do something clever
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about file