当我想运行它时出现此错误:
Exception in thread "main" java.lang.NullPointerException
在这一行
for (File y: childfiles){ )
但奇怪的是,这取决于我选择的方向是否有效
import java.util.*;
import java.io.*;
import java.lang.System;
public class mainclass {
public static void main(String[] args) throws IOException, InterruptedException{
String path = null;
Scanner scan = new Scanner(System.in);
System.out.println("enter path:");
path = scan.nextLine();
File dir = new File(path);
File[] files = dir.listFiles();
for(File x : files){
System.out.println(x);
File[] childfiles = x.listFiles();
for (File y: childfiles){
if(y.toString().endsWith(".exe")){
Process p = Runtime.getRuntime().exec(
y.toString());
p.waitFor();
System.out.println(y.toString()+" executed, press enter for next exe");
scan.nextLine();
}
}
}
}
}
最佳答案
x.listFiles();
将为文件
返回null
(不是目录
)
Returns
null
if this abstract pathname does not denote a directory, or if an I/O error occurs.
因此,在两个循环之前添加如下所示的无效检查
if(files!=null){
}
关于java - 线程 "main"java.lang.NullPointerException 中出现异常,不知道我做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11852304/