2013-10-11 54 views
3

可以使用SeekableByteChannel從文件中讀取行。我有位置(以字節爲單位)並且想要讀取整行。比如我用的RandomAccessFile使用SeekableByteChannel從文件中讀取行

private static String currentLine(String filepath, long currentPosition) 
{ 
    RandomAccessFile f = new RandomAccessFile(filepath, "rw"); 

    byte b = f.readByte(); 
    while (b != 10) 
    { 
    currentPosition -= 1; 
    f.seek(currentPosition); 
    b = f.readByte(); 
    if (currentPosition <= 0) 
    { 
     f.seek(0); 
     String currentLine = f.readLine(); 
     f.close(); 
     return currentLine; 
    } 
    } 
    String line = f.readLine(); 
    f.close(); 
    return line; 

} 

我如何使用像這樣的SeekableByteChannel這種方法,並會更快讀取行龐大的數字?

回答

0

我使用SeekableByteChannel讀取大型文件,比如3GB,並且工作得很好...

try { 
    Path path = Paths.get("/home/temp/", "hugefile.txt"); 
    SeekableByteChannel sbc = Files.newByteChannel(path, 
     StandardOpenOption.READ); 
    ByteBuffer bf = ByteBuffer.allocate(941);// line size 
    int i = 0; 
    while ((i = sbc.read(bf)) > 0) { 
     bf.flip(); 
     System.out.println(new String(bf.array())); 
     bf.clear(); 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
+0

使用,而不是同時請! –

+0

但是這需要所有線路具有相同的長度?! – yankee

+1

讓我們假設文件內部的行長是未知的。最好的方式來實現ByteBuffer.allocate(???)。謝謝 – Al2x