java - 如何确定文件格式? DOS/Unix/MAC

标签 java file format

我编写了以下方法来确定有问题的文件是否使用 DOS/MAC 或 UNIX 行结尾进行格式化。

我至少看到 1 个明显的问题: 1. 我希望我能在第一次运行时获得 EOL,比如在前 1000 个字节内。这可能会发生,也可能不会发生。

我要求您查看此内容并提出改进建议,这将导致强化代码并使其更加通用。

谢谢。

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

然后

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
    }
}

最佳答案

你的方法似乎不必要地复杂。为什么不:

public class FileFormat {
    public enum FileType { WINDOWS, UNIX, MAC, UNKNOWN }

    private static final char CR = '\r';
    private static final char LF = '\n';

    public static FileType discover(String fileName) throws IOException {    

        Reader reader = new BufferedReader(new FileReader(fileName));
        FileType result = discover(reader);
        reader.close();
        return result;
    }

    private static FileType discover(Reader reader) throws IOException {
        int c;
        while ((c = reader.read()) != -1) {
            switch(c) {        
            case LF: return FileType.UNIX;
            case CR: {
                if (reader.read() == LF) return FileType.WINDOWS;
                return FileType.MAC;
            }
            default: continue;
            }
        }
        return FileType.UNKNOWN;
    }
}

这会将其放入静态方法中,然后您可以调用该方法并将其用作:

switch(FileFormat.discover(fileName) {
case WINDOWS: ...
case MAC: ...
case UNKNOWN: ...
}

关于java - 如何确定文件格式? DOS/Unix/MAC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3066511/

相关文章:

java - (ORMLite - android) 直接设置外键字段

java - 如何使用末尾带点的键?

python - 无法从 CPython 读取巨大(20GB)文件

java - 验证字符串输入可能是有效路径

mysql 在将数据集导出到 csv 文件时从文本字段中删除 `CR` 或 `0D`

java - 如何在 Java 中创建特定格式的 JSON 文件

java - 如何获得波斯语地址

java - 在不使用数组的情况下查找列表中与给定元素最近的元素

file - 如何从命令行运行管道 powershell 命令?

format - nim 中的多类型格式化(相当于 boost 格式)