将JTextPane的内容保存到普通文本文件失败

Ker*_*nic 0 java file-io swing 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Tom*_*Tom 5

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

您还可以注销文件的绝对路径以查看它的位置.

    File file =chooserSaveAs.getSelectedFile();
    System.out.println(file.getAbsolutePath());
    FileOutputStream fos = new FileOutputStream(file);
Run Code Online (Sandbox Code Playgroud)

  • 没有必要大喊大叫.你是说你已经尝试过调整过的代码,它写出了文件的位置(即使它不存在)然后在保存之后还没有文件吗? (2认同)