如何从ArrayList获取重复值?

时间:2014-03-23 20:02:58

标签: java arrays file sorting arraylist

有我的代码:

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&#34;照片&#34;, 和目录中目录的第二行&#34;照片/子&#34;我们来看看吧 屏幕:我想你理解了)

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

1 个答案:

答案 0 :(得分:0)

您需要跟踪您在树中的位置,更改find方法以获取路径:

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

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

然后当您添加到列表时,请使用 buffer.add(path + file.getName());