2013-10-11 5 views
3

파일에서 행을 읽는 데 SeekableByteChannel을 사용할 수 있습니까? 위치 (바이트 단위)가 있고 전체 행을 읽고 싶습니다. 예를 들어 나는 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이 같은 것을 사용할 수 있습니다 RandomAccessFile의

이 방법을 사용하고, 라인의 거대한 숫자를 읽는 빨리 될 것인가?

답변

0
내가 3기가바이트 같은 큰 파일을 읽을 SeekableByteChannel을 사용하고 아주 잘 작동하고

... 대신 동안의에 대한

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

관련 문제