如何从数组列表中获得重复的值



这是我的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class CompareFile {
    CompareFile() {}
    boolean check = false;
    int count = 0;
    /*
     * this method return a File type variable
     * variable path - this parameter takes a path in specified root
     * also it's a private method and he should be called with help by class object
     */
    public File find(File path) throws FileNotFoundException {
        PrintWriter writer = new PrintWriter("D:/Photos/name.txt");
        ArrayList<String> buffer = new ArrayList<String>();
        /*
         * let's create array of files
         * where must be all found files
         * We use File[], and named 'files'
         * variable files takes on list of found files
         * with help by listFiles method, that
         * return list of files and directories
         */
        File[] files = path.listFiles();
        //System.out.println(files.toString());
        try {       
            /*
             * we'll ought use the for each loop
             * in this loop we'll create File type variable 'file'
             * then we'll do iterating for each expression from variable files
             */
            for (File file : files) {
                //print all found files and directories
               //if file or directory exists
                if (file.isDirectory()) {
                    //recursively return file and directory
                    find(file);
                } 
                else {
                        buffer.add(file.getName());
                            System.out.println(file);
                }
            }
        }
        catch (Exception e)  {
            System.out.print("Error");
        }
        finally{
            if ( writer != null ) 
                writer.close();
        }

       /*
            Iterator<String> i = buffer.iterator();
                while(i.hasNext()) {
                    System.out.println(i.next());
                }*/
        return path;
    }
    public static void main(String[] args) throws FileNotFoundException  {
        File mainFile = new File("D:/Photos/");
        CompareFile main = new CompareFile();
        main.find(mainFile);
    }
}

如果我使用sort,排序后,结果不好,因为第一行从dir "Photos",第二行来自目录"Photos/sub"让我们看看屏幕:我想你明白了)

http://s10.postimg.org/7hcw83z9x/image.png

您需要跟踪您在树中的位置,将find方法更改为采用路径:

public File find(File path, string path="") throws FileNotFoundException

当你递归调用find方法时:find(file, path + file.getName() + "/")

当你添加到列表中时,使用buffer.add(path + file.getName());

相关内容

  • 没有找到相关文章

最新更新