2017-11-06 4 views
0

다음 MWE는 nio를 사용하여 파일을 작성하는 방법을 보여줍니다. 그러나 파일을 열 때 실패합니다. 디렉토리에 아무런 문제가 없다는 것을 입증하기 위해, 구 학교 파일은 동일한 프로젝트, 동일한 디렉토리에 작성됩니다. NI 코드의 문제점은 무엇입니까?java nio가 파일에 쓰지 못하면 기존 학교 파일이 작동합니다. 무엇이 잘못 되었습니까? '

오류 : "main"스레드의 예외 java.nio.file.NoSuchFileException : test.dat. 이 옵션은 기존 파일에 쓰거나 새 파일을 작성해야하는 CREATE로 설정됩니다. documentation에서

import java.io.*; 
import java.nio.*; 
import java.nio.file.*; 
import java.nio.channels.*; 

public class FastWritenio { 
    public static void writeUsingPrintWriter() throws IOException { 
     PrintWriter pw = new PrintWriter(new FileWriter("test.txt")); 
     pw.print("testing"); 
     pw.close(); 
    } 
    public static void writeUsingnio(int numTrials, int bufferSize, int putsPer) throws IOException { 
     String filename = "test.dat"; 
     java.nio.file.Path filePath = Paths.get(filename); 
     WritableByteChannel channel = Files.newByteChannel(filePath, StandardOpenOption.CREATE); 
     ByteBuffer buf = ByteBuffer.allocate(bufferSize); 
     for (int t = 0; t < numTrials; ++t) { 
      for (int i = 0; i < putsPer; i ++) { 
       buf.putInt(i); 
      } 
      buf.flip(); // stop modifying buffer so it can be written to disk 
      channel.write(buf); // Write your buffer's data. 
     } 
     channel.close(); 
    } 
    public static void main(String[] args) throws IOException { 
     writeUsingPrintWriter(); 
     writeUsingnio(16, 8*1024, 1024); 
    } 
} 
+0

열 수없는 예외는 무엇입니까? – Compass

+0

당신은 저를 때려 눕 힙니다! – Dov

+0

편집을 참조하십시오. 'text.txt! = test.dat' – QBrute

답변

3

Quted :

Both newByteChannel methods enable you to specify a list of OpenOption options. The same open options used by the newOutputStream methods are supported, in addition to one more option: READ is required because the SeekableByteChannel supports both reading and writing.

Specifying READ opens the channel for reading. Specifying WRITE or APPEND opens the channel for writing. If none of these options is specified, the channel is opened for reading.

귀하의 OpenOptions이 부족하다. 예제에서 WritableByteChannel channel = Files.newByteChannel(filePath, StandardOpenOption.CREATE, StandardOpenOption.APPEND);을 설정하면 Windows에 파일이 생성되지만 BufferOverflow으로 끝납니다.

+0

나는 수정 된 코드를 질문에 넣을 예정이다. 작동하기는하지만 우스꽝스럽게 느리다. 그래서 뭔가 잘못되었다고 생각하기 때문이다. – Dov

+1

답변이 당신에게 문제가되는 것이면 언제든지 받아 들여야합니다.) – DrHopfen

+0

@Dov 쓰기 후에 BufferOverflowException을 해결하기 위해'buf.compact()'가 필요합니다. – EJP