java - 如何修复 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
}
}
}
解决方案
你把事情复杂化了。尽管您的 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 *");
}
}
推荐阅读
- python - Python:遍历 CSV 的每一行,计算每一行中的标记,创建一个新的 CSV,其中包含原始 CSV 每一行的标记数
- php - 从 Ajax 原型检索 XML 数据
- php - 如何使用准备好的语句动态绑定参数?
- ios - Swift iOS - 如何为多个类中的不同视频管理 Notification.Name.AVPlayerItemDidPlayToEndTime
- php - php-fpm 环境变量不起作用
- regex - 在日志中搜索 json 的正则表达式
- c - 使用 OpenMP 和 MPI 的混合方法不会在具有不同主机数量的集群中使用相同数量的线程
- python - Make总是在每次运行时调用一些依赖规则
- ios - 获取身份验证失败:invalid_token(受众是项目''但应该是项目'')
- arrays - 使用 Verilog 的 $readmemh 系统任务从文件加载方阵数据