2011-12-21 73 views
2

在windows上使用java和jcifs讀取文件。我需要確定文件的大小,它包含多字節以及ASCII字符。如何根據字符數決定文件大小?

我怎樣纔能有效地實現它或任何現有的API在Java?

感謝,

+1

你需要知道的問題,甚至任何意義的字符編碼。 *你知道編碼嗎? – 2011-12-21 13:27:36

+0

文件大小本身? 'new RandomAccessFile(...)。getChannel()。size()'? – fge 2011-12-21 13:31:50

+0

@fge,如果沒有多字節字符,這沒問題。 – 2011-12-21 13:58:22

回答

1

要獲得字符數,您必須閱讀該文件。通過指定正確的文件編碼,可以確保Java正確讀取文件中的每個字符。

BufferedReader.read()返回讀取的Unicode字符(作爲int,範圍爲0到65535)。所以,簡單的方法來做到這一點會是這樣:

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)是最快的。

(請注意,所有這些例子包括在他們的數行分隔符。)

+0

@thanks sudocode,編寫了類似的代碼。但我很懷疑,所以想檢查其他選項。你的評論確實有幫助。 – Sach 2011-12-22 10:45:13

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 /秒,而磁盤速度測試爲約70-75 MB /秒)

+1

如果您嘗試讀取大文件,是不是會出現內存爆炸? – sudocode 2011-12-21 14:11:30

+1

另外,'new String(ByteBuffer,String)'不能編譯。 – sudocode 2011-12-21 14:47:56

+0

@sudocode感謝您的評論。你是絕對正確的。算法只適用於適合內存的文件(適合99.99%的實際任務)但這是一個很好的評論。關於「新的字符串(字節緩衝區,字符串)」你是對的。我已將其更正爲「新字符串(barray,String)」。謝謝! – andrey 2011-12-22 07:10:35

相關問題