2

在 Windows 上使用 java 和 jcifs 读取文件。我需要确定文件的大小,其中包含多字节以及 ASCII 字符。

我怎样才能有效地实现它或java中的任何现有API?

谢谢,

4

2 回答 2

2

毫无疑问,要获得确切数量的字符,您必须使用正确的编码来阅读它。问题是如何有效地读取文件。Java NIO 是最快的已知方法。

FileChannel fChannel = new FileInputStream(f).getChannel();
    byte[] barray = new byte[(int) f.length()];
    ByteBuffer bb = ByteBuffer.wrap(barray);
    fChannel.read(bb);

然后

String str = new String(barray, charsetName);
str.length();

读取字节缓冲区的速度接近最大可用速度(对我来说,它就像 60 Mb/sec 而磁盘速度测试给出大约 70-75 Mb/sec)

于 2011-12-21T13:46:55.127 回答
1

要获得字符数,您必须阅读文件。通过指定正确的文件编码,可以确保 Java 正确读取文件中的每个字符。

BufferedReader.read()返回读取的 Unicode 字符(作为 0 到 65535 范围内的 int)。所以简单的方法是这样的:

int countCharsSimple(File f, String charsetName) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), charsetName));
    int charCount = 0;
    while(reader.read() > -1) {
        charCount++;
    }
    reader.close();
    return charCount;
}

您将使用Reader.read(char[])获得更快的性能:

int countCharsBuffer(File f, String charsetName) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), charsetName));
    int charCount = 0;
    char[] cbuf = new char[1024];
    int read = 0;
    while((read = reader.read(cbuf)) > -1) {
        charCount += read;
    }
    reader.close();
    return charCount;
}

出于兴趣,我对这两个和安德烈回答中建议的 nio 版本进行了基准测试。我发现上面的第二个示例(countCharsBuffer)是最快的。

(请注意,所有这些示例的计数中都包含行分隔符。)

于 2011-12-21T13:51:32.917 回答