复制D盘下所有的java文件到java.txt文件中,下面是代码- package filedemo;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.FilenameFilter;
- import java.io.IOException;
- public class GetDir {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- // File src = new File("d:\\java_code");
- File src = new File("d:\\");
-
- File dest = new File("java.txt");
- getDir(src,dest);
-
- }
- private static void getDir(File src, File dest) {
- // TODO Auto-generated method stub
- //
- File[] listFiles = src.listFiles();
- for(File f:listFiles){
- if(f.isDirectory()){
- getDir(f,dest);
- }
- else{
- if(f.isFile()&&f.getName().endsWith(".java")){
- copyDir(f,dest);
- }
- }
- }
- // src.listFiles(new FilenameFilter(){
- //
- // @Override
- // public boolean accept(File dir, String name) {
- // // TODO Auto-generated method stub
- // return false;
- // }
- //
- // });
-
- }
- private static void copyDir(File f, File dest) {
- // TODO Auto-generated method stub
- String dir=f.getAbsolutePath();
- FileWriter fw=null;
- try {
- fw = new FileWriter(dest,true);
- fw.write("\r\n");
- fw.write(dir);
- fw.flush();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }finally{
- try {
- fw.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
复制代码 然后,如果源路径是d:\\java_code就可以得出结果,如果是d:\\就会报空指针异常,请大神解惑,O(∩_∩)O谢谢
|
|