首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何区分文本文件?

如何区分文本文件?
EN

Stack Overflow用户
提问于 2011-11-25 07:14:30
回答 1查看 168关注 0票数 0

可能重复:

How do I detect the encoding of some text?

如何区分unicode文本文件和其他文本文件?

我正在使用java做一个批量上传文件。首先,我将输入写入excel文件,然后将其保存为Unicode文本(.txt)文件。然后,我将上传Unicode文本文件,并从我的java类中读取。

我有个问题。我可以区分.txt文件和文本文件以外的其他文件。但是,如何找到一个文件,无论是Unicode文本文件还是其他文本文件。

EN

回答 1

Stack Overflow用户

发布于 2011-11-25 07:59:55

尝尝这个

代码语言:javascript
复制
import org.mozilla.universalchardet.UniversalDetector;

public class TestDetector {
  public static void main(String[] args) throws java.io.IOException {
    byte[] buf = new byte[4096];
    String fileName = args[0];
    java.io.FileInputStream fis = new java.io.FileInputStream(fileName);

    // (1)
    UniversalDetector detector = new UniversalDetector(null);

    // (2)
    int nread;
    while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
      detector.handleData(buf, 0, nread);
    }
    // (3)
    detector.dataEnd();

    // (4)
    String encoding = detector.getDetectedCharset();
    if (encoding != null) {
      System.out.println("Detected encoding = " + encoding);
    } else {
      System.out.println("No encoding detected.");
    }

    // (5)
    detector.reset();
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8265827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档