【问题标题】:How to fix wrong output of content.Equals?如何修复 content.Equals 的错误输出?
【发布时间】:2023-03-26 00:09:01
【问题描述】:

我试图让 Java 读取目录中的所有文件并将文件名与字符串列表进行比较,如果文件名与列表中的字符串相同,它应该输出文件名 +“命中”。现在我只有一个文件。

文件夹命中包含: foto5.jpeg yH1laMN0s7g.jpeg RdrzTHAvcQg.jpeg

列表 lijst.txt 包含: foto5.jpeg yH1laMN0s7g.jpeg RdrzTHAvcQg.jpeg

所以我应该得到: foto5 命中! RdrzTHAvcQg 命中! yH1laMN0s7g 命中!

但我现在得到的是: 照片5 * RdrzTHAvcQg 命中! yH1laMN0s7g *

我尝试过使用编码,现在是 UTF-8。但我不认为这是问题所在。

 public static void main(String[] args) {
    // TODO Auto-generated method stub
    String hit = ""; // empty string

    File files = new File("C:\\Users\\bram\\Pictures\\hit");
    File[] sourceFiles = files.listFiles();  // the files in the map hit java reads

    List<String> lines = new ArrayList<String>();
    try {
        lines = FileUtils.readLines(new File("C:\\lijst.txt"), "utf-8");
    } catch (IOException e2) {
    }  // java reads strings in the list

    for (File x: sourceFiles) {  // java iterates through all the files in the folder hits. 

        String names = x.getName().replaceAll("\\.[^.]*$", "").toString(); 
        // java gets the filenames and converts them to strings without the extension

        for (String a : lines) // for all strings in the list:
        {   
            //System.out.println(a);
            if(names.contentEquals(a))  // if the name is equel to one of the strings in the list it generates a hit
            {
                hit = "Hit!";
            }else {
                hit = "*";              // no hit is * 
            }
        }

    System.out.println(x.getName().replaceAll("\\.[^.]*$", "").toString() +"         "+ hit); // print the results

    }

  }

  }

【问题讨论】:

  • 你试过调试你的代码吗?或者也许只是放一个 sysout 与您正在比较的值并且哪些不相等?我敢打赌它们不相等;-) 如果您怀疑该方法返回错误,可以在此处显示方法 contentEquals(String)
  • 因为你在每一行之后改变你的'hit'变量,所以只输出最后一行的结果。
  • 当我打印名称(字符串)和(字符串)时,我可以看到字符串都是一样的。也许它与Java检查的顺序有关。顺便说一句,我是编程新手 :) 最后一个 sysout 应该是:(names + " " + hit)

标签: java arraylist filenames string-comparison


【解决方案1】:

你把事情复杂化了。尽管您的 txt 文件包含图像文件的全名,但为什么要删除文件扩展名?为什么要嵌套 for 循环?像下面这样的东西还不够吗?

for (File x : sourceFiles) {            
        if(lines.contains(x.getName())){
            System.out.println(x.getName()+"\t Hit!");
        }
        else{
            System.out.println(x.getName()+"\t *");
        }
    }

【讨论】:

  • 是的,我的 txt 文件不包含扩展名。我这边的信息有误,对不起!不过感谢您的回复!
【解决方案2】:

好吧,对不起,伙计们。这是漫长的一天。带有字符串的列表不包含任何扩展名。来自我这边的错误信息,对不起。

我现在可以正常工作了,只需在 for 循环中进行一个简单的中断即可。感谢您的回复!

for (String a : lines) // for all strings in the list:
        {   
            //System.out.println(a);
            if(names.contentEquals(a))  
            {
                hit = "Hit!";
                break;
            }else {
                hit = "*";              // no hit is * 
            }

        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2017-05-27
    • 2019-10-17
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多