파일 랜덤 엑세스

파일 랜덤 엑세스

소스코드

package study.io;

import java.io.IOException;
import java.io.RandomAccessFile;


/**
 * File Random Access 예제
 *
 */
public class RandomFileAccess {

	public RandomFileAccess() {
	}


	/**
	 * 파일을 랜덤하게 읽되, 정해진 position부터 라인단위로 읽는다.
	 *
	 * 가장 마지막으로 file pointer를 위치 시키려면
	 *
	 * file.seek( file.length() )
	 *
	 * 와 같이 표현하면 된다.
	 *
	 * @param filePath
	 * @param position
	 * @return
	 */
	public String readLine( String filePath, long position ) {
		RandomAccessFile file = null;
		try {
			// 파일을 읽기 모드로 연다.
			// 생성자가 반환하는 file 객체는 FileDescriptor이므로,
			// 이후 이 객체를 잘 보관하면서 읽어나가야 File Pointer의 위치를 유지할 수 있다.
			// r: 읽기모드, rw: 읽기쓰기 모드
			file = new RandomAccessFile( filePath, "r" );
			
			// FilePointer를 특정 위치로 Jump 시킨다.
			// Byte단위로 long position값을 넣어야 하므로,
			// File의 encoding에 따라 한 문자가 1byte가 아닐 수도 있으니 주의해야 한다.
			file.seek( position );

			// 한줄(보통 new-line 을 만날 때 까지 )을 읽는다.
			// 이때, File Pointer는 읽은 위치까지 자연스럽게 증가한다.
			return file.readLine();

		} catch( IOException e ) {
			e.printStackTrace( System.err );

		} finally {
			if( file != null ) {
				try {
					file.close();
				} catch( IOException e ) {
					e.printStackTrace( System.err );
				}
			}
		}

		return null;
	}


	public static void main( String[] args ) {
		RandomFileAccess raf = new RandomFileAccess();
		System.out.println( raf.readLine( "c:/temp/mytest.log", 0L ) );
	}

}

실행결과

너무 뻔한 결과니... 직접 파일을 만들어서 실행 해 보세요~

Written with StackEdit.