注:将c盘的根目录封装成File对象后,在运行回报java.lang.NullPointerException
但是如果把目录换成其他的(比如c:\\java),又正常,
不解,请大家帮忙解决下;谢谢
class IOTest{
public static void main(String [] args){
File dir = new File("c:\\");
List<File> list = new ArrayList<File>();
fileoList(dir,list);
File file = new File("c:\\a.txt");
listToFile(list,file.toString());
}
public static void fileoList(File dir,List<File> list){
File [] files = dir.listFiles();
for(File file : files){
if(file.isDirectory())
fileoList(file,list);
else{
if(file.getName().endsWith(".java"))
list.add(file);
}
}
}
public static void listToFile(List<File> list,String filePath){
BufferedWriter bufw = null;
try{
bufw = new BufferedWriter(new FileWriter(filePath));
for(File paths : list){
String path = paths.getAbsolutePath();
bufw.write(path);
bufw.flush();
bufw.newLine();
}
}
catch(IOException e){
throw new RuntimeException("读取数据失败");
}
finally{
try{
if(bufw != null)
bufw.close();
}
catch(Exception e){
throw new RuntimeException("写入流关闭失败");
}
}
}
}
|
|