2013-10-11 57 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