如何在不使用BOM的情况下识别不同的编码?

eyb*_*erg 0 java byte-order-mark utf-8 utf-16

我有一个文件监视器,它正在从使用utf-16LE编码的不断增长的文件中获取内容.写入它的第一位数据有BOM可用 - 我用它来识别UTF-8的编码(我的文件的MOST编码在其中).我抓住了BOM并重新编码为UTF-8,所以我的解析器并没有吓坏.问题是,由于它是一个不断增长的文件,并不是每一位数据都有BOM.

这是我的问题 - 没有将BOM字节添加到我拥有的每组数据(因为我没有对源的控制)我可以只查找UTF-16\000中固有的空字节,然后使用那作为我的标识符而不是BOM?这会让我头疼吗?

我的架构涉及一个ruby Web应用程序,当我用java编写的解析器拾取它时,将收到的数据记录到一个临时文件中.

现在写我的识别/重新编码代码如下所示:

  // guess encoding if utf-16 then
  // convert to UTF-8 first
  try {
    FileInputStream fis = new FileInputStream(args[args.length-1]);
    byte[] contents = new byte[fis.available()];
    fis.read(contents, 0, contents.length);

    if ( (contents[0] == (byte)0xFF) && (contents[1] == (byte)0xFE) ) {
      String asString = new String(contents, "UTF-16");
      byte[] newBytes = asString.getBytes("UTF8");
      FileOutputStream fos = new FileOutputStream(args[args.length-1]);
      fos.write(newBytes);
      fos.close();
    }

    fis.close();
    } catch(Exception e) {
      e.printStackTrace();
  }
Run Code Online (Sandbox Code Playgroud)

UPDATE

我想支持诸如欧元,em-dashes和其他角色之类的东西.我修改了上面的代码看起来像这样,它似乎传递了我对这些字符的所有测试:

  // guess encoding if utf-16 then
  // convert to UTF-8 first
  try {
    FileInputStream fis = new FileInputStream(args[args.length-1]);
    byte[] contents = new byte[fis.available()];
    fis.read(contents, 0, contents.length);
    byte[] real = null;

    int found = 0;

    // if found a BOM then skip out of here... we just need to convert it
    if ( (contents[0] == (byte)0xFF) && (contents[1] == (byte)0xFE) ) {
      found = 3;
      real = contents;

    // no BOM detected but still could be UTF-16
    } else {

      for(int cnt=0; cnt<10; cnt++) {
        if(contents[cnt] == (byte)0x00) { found++; };

        real = new byte[contents.length+2];
        real[0] = (byte)0xFF;
        real[1] = (byte)0xFE;

        // tack on BOM and copy over new array
        for(int ib=2; ib < real.length; ib++) {
          real[ib] = contents[ib-2];
        }
      }

    }

    if(found >= 2) {
      String asString = new String(real, "UTF-16");
      byte[] newBytes = asString.getBytes("UTF8");
      FileOutputStream fos = new FileOutputStream(args[args.length-1]);
      fos.write(newBytes);
      fos.close();
    }

    fis.close();
    } catch(Exception e) {
      e.printStackTrace();
  }
Run Code Online (Sandbox Code Playgroud)

你们都觉得怎么样?

Ste*_*n C 6

通常,您无法100%准确地识别数据流的字符编码.您可以做的最好的事情是尝试使用一组有限的预期编码进行解码,然后对解码结果应用一些启发式方法,以查看它是否看起来像预期语言中的文本.(但任何启发式方法都会给某些数据流带来误报和漏报.)或者,将一个人放入循环中以决定哪个解码最有意义.

更好的解决方案是重新设计协议,以便提供数据的任何内容都必须提供用于数据的编码方案.(如果你不能,责怪谁负责设计/实现无法给你编码方案的系统!).

编辑:根据您对问题的评论,数据文件通过HTTP传递.在这种情况下,您应该安排您的HTTP服务器侦听传递数据的POST请求的"content-type"标头,从标头中提取字符集/编码,并将其保存在文件解析器可以的方式/位置处理.