首页 > 解决方案 > 如何修复 content.Equals 的错误输出?

问题描述

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

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

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

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

但我现在得到的是:foto5 * 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

    }

  }

  }

标签: javaarraylistfilenamesstring-comparison

解决方案


你把事情复杂化了。尽管您的 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 *");
        }
    }

推荐阅读