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

标签 java unit-testing depth-first-search breadth-first-search

我最近在一个类项目上遇到了一些麻烦,确实需要一些帮助。我的老师希望全类同学创建一个用 java 编写的程序,该程序将使用深度优先搜索 (DFS) 定位计算机上最大的文件(具有最长路径的文件),并使用广度优先搜索 (BFS) 创建一个单元测试,以确保我们实际上找到了最大的文件。我尝试研究几个网站来帮助我解决问题,但进展甚微,而且随着截止日期的临近,我开始变得绝望。我会接受任何提供的帮助,谢谢。

编辑:我的老师也提供了这个。

包 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;
    }
}

///////////////和这个////////////////////////////////////////////////////////

包 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);
    }
}

最佳答案

这是让您开始的一个开始。请注意评论:

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;
    }
}

关于java - java中使用dfs和bfs查找计算机上最大的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59219711/

相关文章:

c# - 使用 Moq 模拟带有条件参数的方法

c# - 分布式深度优先搜索

algorithm - 计算节点数 - 有向图中任意两个节点之间的不相交路径,使得距离 <= K

javascript - 如何使用 Javascript 计算一般树中子级的总和

java - Jasper with Spring——来自 org.apache.commons.digester 的大量日志

java - 如何使用 Applescript 或 Java 检查 Mac 上安装的 Adob​​e flash Player?

c# - 在 C# 中的测试运行持续时间内排除测试初始化​​时间

c++ - 单元测试访问者模式架构

java - 用于文本处理(文本挖掘、信息检索、自然语言处理)的 Python 或 Java

java - 提高应用程序性能的方法