【发布时间】: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