2011-12-26 2 views
0

텍스트 파일을 읽은 후 그 파일이 읽혀지는 오프셋을 얻습니다. 다음 프로그램을 시도했지만 그 일은 내가 RandomAccessFile을 사용하고 싶지 않습니다. 어떻게 할 수 있습니까? .파일을 읽은 다음 끝으로 이동

RandomAccessFile access = null; 
       try { 
        access = new RandomAccessFile(file, "r"); 

        if (file.length() < addFileLen) { 
         access.seek(file.length()); 
        } else { 
         access.seek(addFileLen); 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
       String line = null; 
       try { 

        while ((line = access.readLine()) != null) { 

         System.out.println(line); 
         addFileLen = file.length(); 

        } 
+0

RandomAccessFile을 사용하지 않으려면 무엇을 원하십니까? – JRideout

+0

아무거나는 작동 할 것입니다. – Rookie

+1

http://docs.oracle.com/javase/tutorial/essential/io/file.html ByteChannels에 대한 정보 찾기 – Kris

답변

1

파일을 계속 읽으려면 다음을 수행 할 수 있습니다. 이것은 실제로 파일의 끝을 읽지 않음으로써 작동합니다. 당신이 가진 문제는 당신이 완전한 라인이나 완전한 멀티 바이트 문자가 없을 수도 있다는 것입니다.

class FileUpdater { 
    private static final long MAX_SIZE = 64 * 1024; 
    private static final byte[] NO_BYTES = {}; 

    private final FileInputStream in; 
    private long readSoFar = 0; 

    public FileUpdater(File file) throws FileNotFoundException { 
     this.in = new FileInputStream(file); 
    } 

    public byte[] read() throws IOException { 
     long size = in.getChannel().size(); 
     long toRead = size - readSoFar; 
     if (toRead > MAX_SIZE) 
      toRead = MAX_SIZE; 
     if (toRead == 0) 
      return NO_BYTES; 
     byte[] bytes = new byte[(int) toRead]; 
     in.read(bytes); 
     readSoFar += toRead; 
     return bytes; 
    }  
} 
+0

전체 줄을 구문 분석 할 줄 데이터를 얻고 싶습니다. ans는 엄격한 지정에 따라 메일을 보냅니다. 이렇게하면 여분의 오버 헤드가 발생할 것입니다. – Rookie

+0

파일에 전체 행이 있다고 보장 할 수 없으므로 전체 행이 있다고 가정 할 수 없습니다. 대신 데이터를 직접 스캔하고 다음 읽기를 위해 새 줄을 사용하지 않고 바이트를 저장해야합니다. 작은 오버 헤드가 있지만 BufferedReader를 사용하는 것과 거의 동일하며 IO를 읽는 비용과 비교하면 매우 적습니다. –

관련 문제