출처 : 
http://devhome.tistory.com/10 
FileChannel은 
java.nio.channels.FileChannel 에 존재하는 새로운 io 패키지중의 하나이다.

파일 접근적인 속도면에서는 java.io 에서 제공하는 다른 패키지에 비해 성능이 우수하다.

아직은 많이 보편적으로 사용하는 패키지가 아니어 많은 자료를 구하지 못해 간단한 파일을 읽는 방법을 소개한다.


[ 파일읽기 예제소스 ]
01.import java.io.File;
02.import java.io.FileInputStream;
03.import java.io.IOException;
04.import java.nio.ByteBuffer;
05.import java.nio.channels.FileChannel;
06. 
07.public class ObjectTest
08.{
09.public static void main(String args[])
10.{
11.File            inFile   = null;
12.FileInputStream inStream = null;
13.FileChannel     inChannel= null;
14.ByteBuffer      bBuffer  = null;
15.String[]        strBuffer= null;
16. 
17.try
18.{
19.// Open File Channel
20.inFile   = new File("test.txt");
21.inStream = new FileInputStream(inFile);
22.inChannel= inStream.getChannel();
23. 
24.// buffer init...
25.bBuffer = ByteBuffer.allocate((int)inChannel.size());
26.// ANSI & UTF-16 : inChannel.read(bBuffer);
27.// UTF-8         : inChannel.read(bBuffer, 3);
28.inChannel.read(bBuffer);
29. 
30.// casting : ByteBuffer -> String
31.// ANSI   : strBuffer = new String(((ByteBuffer)bBuffer.flip()).array()).split("\r\n");
32.// UTF-8  : strBuffer = new String(((ByteBuffer)bBuffer.flip()).array(), "UTF-8").split("\r\n");
33.// UTF-16 : strBuffer = new String(((ByteBuffer)bBuffer.flip()).array(), "UTF-16").split("\r\n");
34.strBuffer = newString(((ByteBuffer)bBuffer.flip()).array()).split("\r\n");
35. 
36.// print read data from file
37.forint i = 0; i < strBuffer.length; i++ )
38.System.out.println(strBuffer[i]);
39.}
40.catch(IOException e)
41.{
42.e.printStackTrace();
43.return;
44.}
45.finally
46.{
47.try
48.{
49.if( inStream != null )
50.inStream.close();
51.if( inChannel != null )
52.inChannel.close();
53.}
54.catch(IOException e)
55.{
56.e.printStackTrace();
57.return;
58.}
59.}
60.}
61.}

위의 프로그램 소스는 현재 대용량의 파일의 경우는 사용해서는 안돼는 코드이다. 한번에 파일의 전 데이터를
 
읽어오도록 되어 있기때문이다. 그리고 ByteBuffer의 초기화 사이즈는 int형이고 FileChannel의 사이즈는 long형

을 사용하고 있기 때문에 문제가 발생한다.

'자바 > 자바팁' 카테고리의 다른 글

레퍼런스까지 같이 복사하는 Clone 함수 사용법  (0) 2013.06.27
svn 관련 팁  (0) 2012.04.05
NIO가 무엇일까요?  (1) 2012.01.18
자바 NIO 강좌  (0) 2012.01.18
[자바팁]SequenceInputStream example  (1) 2012.01.11

+ Recent posts