我试图浏览目录并打印其中的内容。我试图将它们添加到MessageDigest.update()方法以执行md5检查和。但是,我遇到以下情况错误。
下面提到的是我的代码
public class file_updated {
public static Map extra = new HashMap();
public static void main(String[] args) throws Exception {
File branches = null;
List map_list = new ArrayList();
Map get_val=new HashMap();
List add_apk = new ArrayList();
File f2 = new File("C:\\Users\\rishii\\Desktop\\new_creation");
int count=0;
for (File file : f2.listFiles()) {
branches=getFilesRecursive(file);
add_apk.add(branches);
count=count+1;
}
check_sum(add_apk);
}
public static void check_sum(List file){
try {
MessageDigest Digest = MessageDigest.getInstance("MD5");
Iterator it2 = file.iterator();
int count=0;
while(it2.hasNext())
{
System.out.println(count=count+1);
System.out.println(it2.next().toString());
Digest.update(it2.next().toString().getBytes());
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static File getFilesRecursive(File file)
{
if(file.isDirectory())
{
for(File file1:file.listFiles())
{
return file1;
}
}
return file;
}
}
下面附有我的stackTrace:
java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:854)
at file_updated.check_sum(file_updated.java:61)
at file_updated.main(file_updated.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
答案 0 :(得分:2)
问题是由
引起的 System.out.println(it2.next().toString());
Digest.update(it2.next().toString().getBytes());
您在while循环中调用next()
方法两次。在迭代器上调用next()
是如何获取下一个元素所以在循环中,当你尝试访问迭代器末尾的第二个元素时,你继续获得接下来的2个元素导致java.util.NoSuchElementException
。改为:
while(it2.hasNext()) {
File f = it2.next();
System.out.println(count=count+1);
System.out.println(f.toString());
Digest.update(f.toString().getBytes());
}