如何根据字符数确定文件大小? [英] how determining file size in term of number of characters?

查看:199
本文介绍了如何根据字符数确定文件大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Reading file using java and jcifs on windows. I need to determine size of file, which contains multi-byte as well as ASCII characters.

我该如何有效地实现它或使用Java中的任何现有API?

how can i achieve it efficiently OR any existing API in java?

谢谢

推荐答案

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

To get the character count, you'll have to read the file. By specifying the correct file encoding, you ensure that Java correctly reads each character in your file.

BufferedReader.read( )返回读取的Unicode字符(以0到65535范围内的int形式).因此,简单的方法是这样的:

BufferedReader.read() returns the Unicode character read (as an int in the range 0 to 65535). So the simple way to do it would be like this:

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

出于兴趣,我对这两个基准进行了基准测试,并提出了Andrey答案中建议的nio版本.我发现上面的第二个示例(countCharsBuffer)是最快的.

For interest, I benchmarked these two and the nio version suggested in Andrey's answer. I found the second example above (countCharsBuffer) to be the fastest.

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

(Note that all these examples include line separator characters in their counts.)

这篇关于如何根据字符数确定文件大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆