【问题标题】:Java Netbeans Absolute PathJava Netbeans 绝对路径
【发布时间】:2013-12-16 09:47:01
【问题描述】:

我创建了一个文本编辑器和一个保存按钮,我需要创建一个绝对查找器,这样如果用户没有输入 .txt,程序会自动执行它,因此它始终保存为 txt 文件。请帮忙?

保存按钮的代码

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
    JFileChooser chooseFile = new JFileChooser();
    int choosing = chooseFile.showSaveDialog(this);

    if ( choosing == JFileChooser.APPROVE_OPTION)
    {
        try {
            PrintWriter fileSave = new PrintWriter(chooseFile.getSelectedFile());
            //absolute path ends with 

            fileSave.printf(txtArea.getText());
            fileSave.close();
            txtStatus.setText("Saved");

        } catch (FileNotFoundException ex) {
            Logger.getLogger(TextEditor.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}       

【问题讨论】:

  • 你不能检查chooseFile.getSelectedFile()并在需要时附加“.txt”吗?

标签: java netbeans helper


【解决方案1】:
   import org.apache.commons.io.FilenameUtils;

     File f= chooseFile.getSelectedFile();
    String filePath=f.getAbsolutePath();
    if(!filePath.endsWith("txt")){
    if(FilenameUtils.indexOfExtension(filePath)==-1){//user has other provided extension
        filePath+=".txt";
    }
    }

【讨论】:

  • @user2964786:我删除了代码。您可以使用 JFileChooser 对话框的包装器并覆盖 getSelectedFile() 文件 API
  • 哇,您的代码假定文件扩展名正好是三个字母长。当 Windows 上的文件名通常是 8.3 时,这甚至是危险的,但现在这种情况太多了,所以这个检查会导致更多的问题,然后它解决了。
  • 这好多了 -> +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
  • 1970-01-01
  • 2016-11-23
  • 1970-01-01
相关资源
最近更新 更多