【问题标题】:How to use the searched text file in the if statement condition?如何在if语句条件中使用搜索到的文本文件?
【发布时间】:2014-02-25 20:01:53
【问题描述】:

这是我用它的文件名搜索文本文件的代码。 该程序没有错误,但我不知道代码是否正确搜索。如果文件存在,如果在消息对话框中不存在“找不到文件”,我想得到消息“找到文件”。所以任何对我的困难有想法的人请帮助我。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    File dir = new File("C:\\Users\\EmuD\\Documents\\NetBeansProjects\\Bank Project");
    File[] matchingFiles = dir.listFiles(new FilenameFilter() {

        public boolean accept(File dir, String name) {
            String search = jTextField1.getText();
            return name.startsWith(search) && name.endsWith(".txt");
        }
    });
}

非常感谢!!

【问题讨论】:

  • 有什么难度?

标签: java swing search message


【解决方案1】:

File 有一个 exists() 方法。要从这些参数中获取 File,请创建一个新文件。代码类似于boolean fileExists = new File(dir, fileName).exists();

我猜您不是在寻求有关如何在 JLabel 中显示测试的帮助。

【讨论】:

    【解决方案2】:

    你的问题可以在here找到答案:

    File f = new File(filePathString);
    if(f.exists() && !f.isDirectory()) { /* do something */ }
    

    你不应该只使用File.exists(),因为它也为目录返回true。由于您只对文件感兴趣,因此您需要第二次检查!File.isDirectory()

    【讨论】:

      猜你喜欢
      • 2019-09-10
      • 2017-10-30
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多