自己做的一个遍历程序,将指定目录下的所有文件及其子目录的所有文件复制粘贴放在一个目录下,这个目录会自动根据说复制文件的后缀名分类放入指定目录,表达不是很清楚,请看代码:
package com.ctbu.butterfly;import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class AllClass {
public String getlname(File f) {
String name;
name = f.getName();
name = name.substring(name.lastIndexOf(".") + 1, name.length());
return name;
} public String getDir(String name) {
File dirs = new File("D:/目录集合/" + name);
if (!dirs.exists())
dirs.mkdirs();
return dirs.getPath();
} public void copy(String path) {
int i;
byte[] buf;
FileInputStream in = null;
FileOutputStream out = null;
File[] files = new File(path).listFiles();
                           //下面这行NullPointerException
for (i = 0; i < files.length; i++) {
if (files[i].isFile() && files[i].canRead()
&& files[i].canWrite() && !files[i].exists()) {
getDir(getlname(files[i]));
try {
in = new FileInputStream(files[i]);
buf = new byte[(int) (files[i].length())];
in.read(buf);
out = new FileOutputStream(getDir(getlname(files[i]))
+ "/" + files[i].getName());
out.write(buf);
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if (files[i].isDirectory())
                   //下面这行NullPointerException,改成
                   //System.out.println(path  + files[i].getName()+ "/")能正确输出目录,求解
copy(path  + files[i].getName()+ "/");
}
}
package com.ctbu.butterfly;public class Test {
public static void main(String[] args) {
AllClass ac=new AllClass();
ac.copy("D:/");
}
}
}

解决方案 »

  1.   

    public class FilesClassify { static String getLastName(File file){
    String name = file.getName();
    int index = name.lastIndexOf('.');
    if(index>=0){
    return name.substring(index+1);
    }
    return name;
    }

    /**
     * @param srcRoot 源目录,即等待文件分类的目录(文件夹)
     * @param destRoot 目标目录,即分类存放的目录
     */
    public void classify(String srcRoot, String destRoot) throws IOException{
    classify(new File(srcRoot),new File(destRoot));
    }

    public void classify(File srcRoot, File destRoot) throws IOException{
    File srcFiles [] = srcRoot.listFiles();
    for(File f : srcFiles){
    if(f.isDirectory()){
    classify(f, destRoot);
    }else{
    File des = new File(destRoot.getPath()+File.separator+getLastName(f));
    if(!des.exists()){
    des.mkdirs();
    }
    if(f.getParent().equals(des))return;
    copy(f,new File(des.getPath()+File.separator+f.getName()));
    }
    }
    } private boolean copy(File src, File dest) throws IOException{
    long len = src.length();
    FileChannel in = new FileInputStream(src).getChannel();
    FileChannel out= new FileOutputStream(dest).getChannel();
    long size = in.transferTo(0, len, out);
    return len==size;
    }

    public static void main(String [] args ) throws IOException{
    new FilesClassify().classify("D:\\1", "D:\\2");
    }
    }
      

  2.   

    引用你的代码:
    File[] files = new File(path).listFiles();
    //下面这行NullPointerException
    for (i = 0; i < files.length; i++) {
    ...
    }listFiles
    public File[] listFiles()返回一个抽象路径名数组,这些路径名表示此抽象路径名所表示目录中的文件。 
    如果此抽象路径名并不表示一个目录,则此方法将返回 null。否则,为目录中的每个文件或目录返回一个 File 对象数组。表示目录本身及其父目录的路径名不包括在结果中。得到的每个抽象路径名都是根据此抽象路径名,使用 File(File, String) 构造方法构造。所以,如果此路径名是绝对路径名,则得到的每个路径名都是绝对路径名;如果此路径名是相对路径名,则得到的每个路径名都是相对于同一目录的路径名。 不保证所得数组中的相同字符串将以特定顺序出现,特别是不保证它们按字母顺序出现。 返回:
    表示此抽象路径名所表示目录中的文件和目录的抽象路径名数组。如果目录为空,则数组也将为空。如果抽象路径名不表示一个目录,或者发生 I/O 错误,则返回 null。 

    抛出: 
    SecurityException - 如果存在安全管理器,且其 SecurityManager.checkRead(java.lang.String) 方法拒绝对目录进行读取访问
    从以下版本开始: 
    1.2 当返回空时,你再遍历,就会出现NullPointerException了,所以,你应该在遍历前先加空判断。
      

  3.   


    package com.iwgod.a;import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;/**
     *  I/O 流复制一个文件夹
     * @author 随想
     *
     */
    public class CopyFiles {
    public static void main(String[] args) {
    CopyFiles.copy(new File("C:/Inetpub"), new File("D:/"));
    }
    /**
     * 功能描述:拷贝一个目录或者文件到指定路径下,即把源文件拷贝到目标文件路径下
     * 递归实现 
     * @param source  源文件
     * @param target 目标文件路径
     * @return void
     */
    public static void copy(File source, File target) {
    File tarpath = new File(target, source.getName());
    if (source.isDirectory()) {
    tarpath.mkdir();
    File[] dir = source.listFiles();
    for (int i = 0; i < dir.length; i++) {
    System.out.println(" 拷贝中 "+dir[i].getPath()+" --到文件夹--> "+tarpath);
    copy(dir[i], tarpath);
    }
    } else {
    try {
    InputStream is = new FileInputStream(source); // 用于读取文件的原始字节流
    OutputStream os = new FileOutputStream(tarpath); // 用于写入文件的原始字节的流
    byte[] buf = new byte[1024];// 存储读取数据的缓冲区大小
    int len = 0;
    while ((len = is.read(buf)) != -1) {
    os.write(buf, 0, len);
    }
    is.close();
    os.close();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }
      

  4.   

    你的代码classify(new File(srcRoot),new File(destRoot));
    和for(File f : srcFiles)  
    跟我一样是NullPointerException
      

  5.   

    把你的代码下来测试了下,只要修改一个地方就OK
     if (files[i].isFile() && files[i].canRead()
                            && files[i].canWrite() && !files[i].exists())!files[i].exists()  把这个判断条件修改成 files[i].exists()测试了下,将我一个目录下的word、ppt、xls文件都分到了D:\目录集合,并且下面分了三个子文件夹:
    xls、doc、ppt
    文件整齐的归类放了进去
      

  6.   


    十分感谢,我代码那里加了
    if(files!=null)
    for (i = 0; i < files.length; i++)
    就完全可以了,谢谢,没想过子目录可能是空的,感谢