2013-03-27 1 views
0

실패 :저장 JTextPane가의 내용은 내가 코드의 덩어리 다음 한

private void saveAs() 
{ 
    CDocument currentDocument=this.panelMain().openedDocuments().get(this.panelMain().openedDocuments().size()-1); 
    StyledDocument contents=currentDocument.getStyledDocument(); 
    DefaultEditorKit kit=new DefaultEditorKit(); 
    JFileChooser chooserSaveAs=new JFileChooser(); 

    chooserSaveAs.setDialogTitle("Save as ..."); 
    if(chooserSaveAs.showSaveDialog(this)==JFileChooser.APPROVE_OPTION) 
    { 
     String strNewFilename=chooserSaveAs.getSelectedFile().getName(); 
     BufferedOutputStream out; 

     try 
     { 
      out=new BufferedOutputStream(new FileOutputStream(strNewFilename)); 
      kit.write(out, 
        contents, 
        contents.getStartPosition().getOffset(), 
        contents.getLength()); 
      out.close(); 
     } 
     catch(IOException | BadLocationException ex) 
     { 
      Logger.getLogger(CFrameMain.class.getName()).log(Level.SEVERE, 
        null, 
        ex); 
     } 
    } 
} 

가 실행되면,이 코드는 예외를 생성하지 않습니다,하지만 난 아무데도 디스크에 파일을 저장 찾을 수 없습니다 (내가 검색 한 총 사령관과 로컬 디스크를 통해). 생성 된 파일이없는 이유는 무엇입니까? 현재 Windows 7 Ultimate에서 작업 중이며 로그온 한 사용자의 데스크톱에 저장하려고했습니다 (가능한 액세스 위반 문제로 인해 ...)?

+1

[SSCCE] (http://sscce.org/)에서 문제를 보여주는 글을 게시하십시오. – camickr

+0

당신은 out.flush() 호출하려고 할 수 있습니다; 끝나기 전에? – StanislavL

답변

0

아니요, 문제를 해결할 수있었습니다. @ Tom의 접근 방식을 사용했고 작동합니다! 코드 덩어리는 다음과 같습니다.

try 
    { 
     out=new BufferedOutputStream(new FileOutputStream(file)); 
     kit.write(out, 
        contents, 
        contents.getStartPosition().getOffset(), 
        contents.getLength()); 
     out.close(); 
    } 
    catch(IOException | BadLocationException ex) 
    { 
     bError=true; 
     Logger.getLogger(CFrameMain.class.getName()).log(Level.SEVERE, 
         null, 
         ex); 
    } 
    finally 
    { 
      if(bError!=true) 
      { 
         currentDocument.setFilename(chooserSaveAs.getSelectedFile().getAbsolutePath()); 
         this.toolBarFileSwitcher().listOpenedFiles().model().set(this.toolBarFileSwitcher().listOpenedFiles().getSelectedIndex(), 
          currentDocument.filename()); 
        this.toolBarFileSwitcher().updateUI(); 
      } 
    } 
+0

코드 서식을 사용하는 방법을 배우십시오. 코드 샘플을 선택하고'{}'버튼을 클릭하십시오. –

+0

'updateUI()'메소드를 사용할 필요가 없습니다. 필요하다고 생각되면 코드에 다른 논리 오류가 있습니다. – camickr

5

파일 이름을 가져 오지 마시고 올바른 위치에 저장해야합니다.

또한 파일의 절대 경로를 로그 아웃하여 위치를 확인할 수 있습니다.

File file =chooserSaveAs.getSelectedFile(); 
    System.out.println(file.getAbsolutePath()); 
    FileOutputStream fos = new FileOutputStream(file); 
+0

하지만 저장 시간에 파일이 존재하지 않습니다! – KernelPanic

+2

고함을지를 필요가 없습니다. 편집 된 코드를 시도했는지, 파일의 위치를 ​​썼는지 (존재하지 않더라도) 쓴 다음 저장 후에도 파일이 남아 있지 않다는 말입니까? – Tom