2013-03-27 91 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); 
     } 
    } 
} 

一旦执行,该代码不会产生任何异常,但我无法找到保存在磁盘上文件的任何地方(我搜索通过本地磁盘与Total Commander)。为什么没有生成文件?我目前正在使用Windows 7旗舰版,并试图保存到登录用户的桌面(因为可能的访问冲突问题......)?

+1

发布您的[SSCCE](http://sscce.org/),演示问题。 – camickr 2013-03-27 05:04:01

+0

你可以尝试调用out.flush();结束之前? – StanislavL 2013-03-27 05:55:22

回答

0

不,但我设法解决它。我用@汤姆的方法,它的工作原理!这里是代码块:

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

请了解如何使用代码格式。选择代码示例并点击'{}'按钮。 – 2013-03-27 21:33:45

+0

没有必要使用'updateUI()'方法。如果你认为你需要它,那么你的代码中有一些其他的逻辑错误。 – camickr 2013-03-28 03:28:38

5

获取文件不是名称,它应该保存到正确的位置。

此外,您还可以注销文件的绝对路径以查看其位置。

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

但是文件不存在保存时间! – KernelPanic 2013-03-27 04:20:20

+2

有没有必要喊。你是说你已经尝试过调整后的代码,它写出了文件的位置(即使它不存在),然后在保存之后还没有文件? – Tom 2013-03-27 05:26:17

相关问题