2015-01-02 6 views
1

메모리 매핑 된 쓰기를 수행하기 위해 fileChannel을 만들고 있습니다. 이 fileChannel의 크기는 100 바이트입니다. 나는 그것에 80 바이트만을 쓴다. 그래서 나중에 그 파일을 읽을 때, and에 5 "0"이 추가됩니다. 크기를 설정하거나 크기를 파일에 기록 할 수있는 방법이 있습니까?내용보다 큰 Java FileChannel

감사합니다.

public FileChannel create(String randomFile){ 
    // create file output stream 
    RandomAccessFile raf; 
    FileChannel fc = null; 

    try {  
     raf = new RandomAccessFile(randomFile, "rw"); 
     fc = raf.getChannel(); 
     System.out.println("fc.size() "+ fc.size());  
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return fc; 
} 
+0

왜'FileChannel.open()'을 사용하지 않으시겠습니까? – fge

+0

FileChannel을 사용하여 MappedByteBuffer.mbb = fc.map (MapMode.READ_WRITE, position, bufferSize);을 만든 다음 해당 버퍼에 쓰기 –

답변

2

사용이 대신 :

final Path path = Paths.get("thefile"); 
final FileChannel fc = FileChannel.open(path, StandardOpenOption.WRITE, 
    StandardOpenOption.READ); 

// then later: 

fc.truncate(80L); 

그리고 물론

.close()하는 것을 잊지 마십시오. 이상적으로는 리소스 사용 시험을 통해 채널을 열어야합니다.

+0

다음과 같은 경우이 오류가 발생합니다. FileChannel 유형의 메소드 open (Path, OpenOption ...)이 인수 (Path, FileChannel.MapMode)에 적용되지 않습니다. –

+0

아, 음, javadoc을 간략하게 살펴 보겠습니다. 뭐가 잘못 됐는지, 사실은 오류라고 말해 줬어. 'FileChannel.MapMode.WRITE'를'StandardOpenOption.WRITE'로 대체하십시오. – fge

+0

죄송합니다, 당신 말이 맞습니다. 이제 파일을 메모리에 매핑 할 수 없다는 문제가 생겼습니다 :'MappedByteBuffer mbb = fc.map (MapMode.READ_WRITE, position, bufferSize);'이것은 nonReadableChannel Exception을 던졌습니다. 이유를 모르겠습니다 ... –

0

내 생각에 setLength()이 (가) 찾고 있습니다. Java doc.

+0

이것은 100 바이트를 반환합니다. 파일에 쓰기 시작하기 전에. –