简体   繁体   English

在java中使用dfs和bfs在计算机上查找最大文件

[英]Find largest file on computer with dfs and bfs in java

I have been having some trouble with a class project lately and could really use some help.我最近在一个班级项目上遇到了一些麻烦,真的需要一些帮助。 My teacher wants the class to create a program written in java that will locate the largest file (file with the longest path) on our computers using depth first search (DFS) and create a unit test with a breadth first search (BFS) to ensure that we have in fact found the largest file.我的老师希望班级创建一个用 Java 编写的程序,该程序将使用深度优先搜索 (DFS) 定位我们计算机上最大的文件(具有最长路径的文件),并创建一个具有广度优先搜索 (BFS) 的单元测试以确保我们实际上找到了最大的文件。 I have tried researching several websites to help me solve my problem but have made very little progress and with the due date coming up I am starting to get desperate.我曾尝试研究几个网站来帮助我解决我的问题,但进展甚微,随着截止日期的临近,我开始感到绝望。 I will accept any help provided, thank you.我会接受提供的任何帮助,谢谢。

edit: My teacher has also provided this.编辑:我的老师也提供了这个。

package edu.gcccd.csis;包 edu.gcccd.csis;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;


/**
 * Finds the largest file using DFS.
 */
public class Finder {


    /**
     * If no start location is given, the we start the search in the current dir
     *
     * @param args {@link String}[] start location for the largest file search.
     */
    public static void main(final String[] args) {
        final Path path = Paths.get(args.length < 1 ? "." : args[0]);
        final File ex = findExtremeFile(path);
        System.out.printf("Starting at : %s, the largest file was found here:\n%s\n its size is: %d\n",
                path.toAbsolutePath().toString(),
                ex.getAbsolutePath(),
                ex.length());
    }


    /**
     * Identifies the more extreem of two given files.
     * Modifying this method allows to search for other extreems, like smallest, oldest, etc.
     *
     * @param f1 {@link File} 1st file
     * @param f2 {@link File} 2nd file
     * @return {@link File} the more extreme of the two given files.
     */
    static File extreme(final File f1, final File f2) {
        // ...
    }


    /**
     * DFS for the most extreme file, starting the search at a given directory path.
     *
     * @param p {@link Path} path to a directory
     * @return {@link File} most extreme file in the given path
     */
    static File findExtremeFile(final Path p) {
        File x = null;
        final File[] fa = p.toFile().listFiles();
        if (fa != null) { // if null then directory is probably not accessible
            //
            // Since this is DFS, first find all sub-directories in the current directory
            //


                ..
            //
            // Now let's look at al the files in the current dir
            //
                ..
        }
        return x;
    }
}

///////////////and this /////////////////////////////////////////////////////// ///////////////和这个 ///////////////////////////////// //////////////////////

package edu.gcccd.csis;包 edu.gcccd.csis;

import org.junit.Test;


import java.io.File;
import java.io.FileWriter;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


import static org.junit.Assert.assertEquals;


public class FinderTest {


    /**
     * BFS implementation to find extreme file
     *
     * @param p {@link Path} starting path
     * @return {@link File} extreme file
     */
    @SuppressWarnings({"unchecked"})
    private static File findExtremeFile(final Path p) {
        final List fileList = new ArrayList();
        fileList.add(p.toFile());


        ...




        return x;
    }




    /**
     * Verify that the extreme method identifies the largest etc etc. file
     */
    @Test
    public void testExtreme() throws Exception {
        // check what happens if one file is null ..
        File f1 = null;
        final File f2 = File.createTempFile("test2_", ".tmp");
        f2.deleteOnExit();


        assertEquals(f2, Finder.extreme(f1, f2));
        assertEquals(f2, Finder.extreme(f2, f1));


        //  check what happens if both files have the same length (like 0)




        ...




        // check what happens if one file is larger
        // .. how to add content to a (tmp-)file:
        // https://www.baeldung.com/java-write-to-file




        ...


        assertEquals(f2, Finder.extreme(f2, f1));
        assertEquals(f2, Finder.extreme(f1, f2));
    }


    /**
     * Verify that DFS and BFS return the same result.
     */
    @Test
    public void findExtremeFile() throws Exception {
        // find a reasonable place to start the search .. or hard code is this doesn't work
        final File f2 = File.createTempFile("test", ".tmp");
        f2.deleteOnExit();


        final Path p = f2.getParentFile().getParentFile().toPath();
        final File extreme1 = Finder.findExtremeFile(p);
        final File extreme2 = FinderTest.findExtremeFile(p);
        assertEquals(extreme1, extreme2);
    }
}

Here is a start to get you going.这是让你前进的开始。 Please note the comments:请注意以下评论:

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedList;

/**
 * Finds the largest file using DFS.
 */
public class Finder {

    /**
     * If no start location is given, the we start the search in the current dir
     *
     * @param args {@link String}[] start location for the largest file search.
     */
    public static void main(final String[] args) {
        Path path = Paths.get(args.length < 1 ? "." : args[0]);
        final File ex = findExtremeFile(path);
        System.out.printf("Starting at : %s, the largest file was found here:\n%s\n its size is: %d\n",
                path.toAbsolutePath().toString(),
                ex.getAbsolutePath(),
                ex.length());
    }

    /**
     * Identifies the more extreme of two given files.
     * Modifying this method allows to search for other extremes, like smallest, oldest, etc.
     *
     * @param f1 {@link File} 1st file
     * @param f2 {@link File} 2nd file
     * @return {@link File} the more extreme of the two given files.
     */
    static File extreme(final File f1, final File f2) {

        //if one file is not a valid file, return the other
        if (f1 == null || !f1.exists() ||  !f1.isFile() ){
            if (f2 != null && f2.exists() && f2.isFile()) return f2;
            else throw new IllegalArgumentException();
        }

        if (f2 == null || !f2.exists() ||  !f2.isFile() ){
            if (f1 != null && f1.exists() && f1.isFile()) return f1;
            else throw new IllegalArgumentException();
        }

        //return the largest file
        return f1.length() > f2.length() ? f1 : f2 ;
    }

    /**
     * DFS for the most extreme file, starting the search at a given directory path.
     *
     * @param p {@link Path} path to a directory
     * @return {@link File} most extreme file in the given path
     */
    static File findExtremeFile(final Path p) {

        File x = null; //extreme file
        final LinkedList<File> stack = new LinkedList<>(); //stack for directories
        stack.push(p.toFile());
        //implement dfs
        while (! stack.isEmpty()){
            File dir = stack.pop();
            final File[] fa = dir.listFiles();
            if (fa == null) {
                continue;  // if null then directory is probably not accessible
            }

            for(File f : fa){
                if(f.isDirectory()) { //if directory push to stack
                    stack.push(f);
                    continue;
                }
                //if not directory check if extreme
                if(x != null) {
                    x = extreme(x, f);
                }
                else {
                    x =  f; //for first time
                }
            }
        }
        return x;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM