2016-06-10 1 views
0

일부 사용자 메뉴 선택에 따라 업데이트하고 싶은 파일이 있습니다. 내 코드가 존재하지 않으면 IFile 이 생성되고 (사용자의 콘텐츠와 함께), 존재한다면 업데이트해야합니다. 내 현재 코드는 다음과 같습니다업데이트 일식 플러그인의 IFile 콘텐츠

String userString= "original String"; //This will be set by the user 
    byte[] bytes = userString.getBytes(); 
    InputStream source = new ByteArrayInputStream(bytes); 
    try { 
     if(!file.exists()){ 
      file.create(source, IResource.NONE, null); 
     } 
     else{ 
      InputStream content = file.getContents(); 
      //TODO augment content 
      file.setContents(content, 1, null); 
     } 

    } catch (CoreException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    try { 
     IDE.openEditor(page, file); 

내 문제는 내가 원래 콘텐츠를하고 파일의 내용을 설정하더라도, 내가 즉, 업데이트시 빈 파일을 얻고, 전체 내용이 삭제되는 것입니다.

내가 뭘 잘못하고 있니?

+1

그 코드는 파일이 이미 존재하는 경우 파일 내용을 기존 내용으로 설정합니다. 그러나 나는 당신이 동시에 파일을 읽고 쓰고 있기 때문에 파일을 잘라 버릴 수도 있다고 생각합니다. 파일이 이미 있다면 실제로 무엇을하고 싶습니까? –

+0

안녕하세요. 미안 내 게시물이 명확하지 않은 경우 // TODO 증가 내용이 있습니다. 사용자 입력을 기반으로 현재 파일 내용을 가져오고 현재 입력 한 내용을 사용자 입력에 추가하고 새 파일로 설정합니다. 함유량. 동기화 문제를 피하고자 할 때 가장 좋은 방법은 콘텐츠를 가져 와서 변경하고 다시 설정하는 것입니다. 그러나 내용을 설정할 때 빈 파일이 나타납니다. – Quantico

+2

읽은 후에'content.close()'를 호출 했습니까? –

답변

2

귀하의 코멘트에있는 코드의이 버전은 나를 위해 작동 :

InputStream inputStream = file.getContents(); 

StringWriter writer = new StringWriter(); 

// Copy to string, use the file's encoding 
IOUtils.copy(inputStream, writer, file.getCharset()); 

// Done with input 
inputStream.close(); 

String theString = writer.toString(); 

theString = theString + " added"; 

// Get bytes using the file's encoding 
byte[] bytes = theString.getBytes(file.getCharset()); 

InputStream source = new ByteArrayInputStream(bytes); 

file.setContents(source, IResource.FORCE, null); 

참고 원래의 입력 스트림의 가까이 file.getCharset()의 사용이 올바른 인코딩을 사용합니다.

+0

inputStream.close()가 누락되었습니다. – Quantico