在目录中搜索.txt文件,而不需要完整的路径名。-JAVA

在目录中搜索.txt文件,而不需要完整的路径名。-JAVA,java,file-io,Java,File Io,我编写了一个文件写入脚本,允许您在控制台中写入正在查找的文件,然后当您按enter键时,它会尝试查找该文件以查看它是否存在。我的程序可以运行,但我不喜欢这样,每次我都需要完整的路径名。我希望用户能够编写,比如说,文件_name.txt,然后程序在单个目录中搜索它 目前,我每次都必须使用完整的路径名。这不是我的全部代码,但您可以看到我的文件名有一个硬编码字符串路径名。但是如果其他人想在他们自己的计算机上运行这个程序呢?我试图寻找这个问题的答案,但Java对我来说总是很难。如果您知道一种方法使我的代

我编写了一个文件写入脚本,允许您在控制台中写入正在查找的文件,然后当您按enter键时,它会尝试查找该文件以查看它是否存在。我的程序可以运行,但我不喜欢这样,每次我都需要完整的路径名。我希望用户能够编写,比如说,文件_name.txt,然后程序在单个目录中搜索它

目前,我每次都必须使用完整的路径名。这不是我的全部代码,但您可以看到我的文件名有一个硬编码字符串路径名。但是如果其他人想在他们自己的计算机上运行这个程序呢?我试图寻找这个问题的答案,但Java对我来说总是很难。如果您知道一种方法使我的代码足够通用,这样我的Scanner对象就可以只使用文件名,那将非常有用。谢谢,如果有什么不清楚的请告诉我。我有一台Mac电脑,但它应该可以在任何操作系统上工作

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.util.Scanner;


public class FileHandler {
    public static boolean fileCheck = true;
    public static File logFile;
    public static PrintWriter logPrinter;
    public static PrintWriter handMadeFile;
    public static LocalDate date = LocalDate.now();
    public static File fileFromScanner;
    public static File directory = new File("/Users/mizu/homework");
    public static String fileName;
    public static File file;
    public static String created = "Log has been created.";
    public static String myLogFileName = "/Users/mizu/homework/my_log.txt";
    public static String mainFileName = "/Users/mizu/homework/main_file.txt";
    public static String fileFromMethod = "/Users/mizu//homework/file_from_method.txt";
    public static String fileMessage = "I just wrote my own file contents.";


    public static void main(String[] args) {

        if (!directory.exists())
        {
            // create new directory called homework
            directory.mkdir();
        }

        // gets file request from user
        System.out.print("Enter file to find: ");
        Scanner in = new Scanner(System.in);
        String fileName = in.nextLine();

        // initialize the main_file
        fileFromScanner = new File(mainFileName);

        // if main_file exists or not, print message to my_log
        if (!fileFromScanner.exists())
        {
            // create my_log file (logFile), to keep track of events
            writeToLog(created);
            writeToLog("File path you entered: "
                    + fileName + " does not exist.");
            System.out.println(fileName + " - does not exist.");

            // create file since it doesn't exist
            File mainFile = new File(mainFileName);
            try {
                PrintWriter pwMain = new PrintWriter(new BufferedWriter
                        (new FileWriter(mainFile)));
                writeToLog("Created " + mainFileName);
                pwMain.close();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else
        {
            writeToLog(fileName + " already exists.");
            System.out.println(fileName + " - already exists.");
        }

        // use writeToFile method to write file, create new file name
        FileHandler testFile = new FileHandler(fileFromMethod);
        testFile.writeToFile(testFile, fileMessage);

    } // end Main

下面列出了所有其他方法,但没有简要说明。

1-您可以让用户将环境变量设置为路径,并在代码中使用路径名

2-您可以检查操作系统,并将文件放在一个众所周知的文件夹中。C:对于windows,/home for Ubuntu,/WhateverMacFolder for mac,如果是其他操作系统,请用户输入路径


3-您可以在程序的默认路径中创建文件夹并使用它

1-您可以让用户将环境变量设置为path,并在代码中使用路径名

2-您可以检查操作系统,并将文件放在一个众所周知的文件夹中。C:对于windows,/home for Ubuntu,/WhateverMacFolder for mac,如果是其他操作系统,请用户输入路径


3-您可以在程序的默认路径中创建文件夹并使用它

如评论中所述,已有多种工具可用于搜索目录中的文件。然而,为了回答您的问题,我编写了一个简单的程序,它应该满足您的需求:

public static void main(String[] args) {
    // Get the absolute path from where your application has initialized
    File workingDirectory = new File(System.getProperty("user.dir"));
    // Get user input
    String query = new Scanner(System.in).next();
    // Perform a search in the working directory
    List<File> files = search(workingDirectory, query);
    // Check if there are no matching files
    if (files.isEmpty()) {
        System.out.println("No files found in " + workingDirectory.getPath() + " that match '"
                + query + "'");
        return;
    }
    // print all the files that matched the query
    for (File file : files) {
        System.out.println(file.getAbsolutePath());
    }
}

public static List<File> search(File file, String query) {
    List<File> fileList = new ArrayList<File>();
    // Get all the files in this directory
    File[] files = file.listFiles();
    if (files != null) {
        for (File f : files) {
            if (f.isDirectory()) {
                // use recursion to search in all directories for the file
                fileList.addAll(search(f, query));
            } else if (f.getName().toLowerCase().contains(query.toLowerCase())) {
                // if the filename matches the query, add it to the list
                fileList.add(f);
            }
        }
    }
    return fileList;
}

如评论中所述,已有多种工具可用于搜索目录中的文件。然而,为了回答您的问题,我编写了一个简单的程序,它应该满足您的需求:

public static void main(String[] args) {
    // Get the absolute path from where your application has initialized
    File workingDirectory = new File(System.getProperty("user.dir"));
    // Get user input
    String query = new Scanner(System.in).next();
    // Perform a search in the working directory
    List<File> files = search(workingDirectory, query);
    // Check if there are no matching files
    if (files.isEmpty()) {
        System.out.println("No files found in " + workingDirectory.getPath() + " that match '"
                + query + "'");
        return;
    }
    // print all the files that matched the query
    for (File file : files) {
        System.out.println(file.getAbsolutePath());
    }
}

public static List<File> search(File file, String query) {
    List<File> fileList = new ArrayList<File>();
    // Get all the files in this directory
    File[] files = file.listFiles();
    if (files != null) {
        for (File f : files) {
            if (f.isDirectory()) {
                // use recursion to search in all directories for the file
                fileList.addAll(search(f, query));
            } else if (f.getName().toLowerCase().contains(query.toLowerCase())) {
                // if the filename matches the query, add it to the list
                fileList.add(f);
            }
        }
    }
    return fileList;
}

搜索整个计算机可能需要很长时间。嗯,也许这是一个很好的观点。与其重新发明轮子,还有很多小程序已经在做这个了。示例:查找根据您启动程序的方式,从您要查找的文件所在的目录启动程序可能会更容易,或者可能会添加一个文件浏览器对话框,让用户以图形方式选择它?谢谢Evan,听起来不错。不过,我只是在Eclipse中创建一个Java应用程序,这是一个我需要做的作业,不幸的是,我不知道如何做图形。有没有办法把搜索范围缩小到一个目录?就像用户可以键入文件_name.txt,它将只在一个目录中搜索一样?听起来很简单,但我不知道怎么做。现在,必须在控制台中键入完整路径名,以便进行完整路径名搜索。我只想在控制台中使用文件名。搜索整个计算机可能需要很长时间。嗯,也许这是一个好的观点。与其重新发明轮子,还有很多小程序已经做到了这一点。示例:查找根据您启动程序的方式,从您要查找的文件所在的目录启动程序可能会更容易,或者可能会添加一个文件浏览器对话框,让用户以图形方式选择它?谢谢Evan,听起来不错。不过,我只是在Eclipse中创建一个Java应用程序,这是一个我需要做的作业,不幸的是,我不知道如何做图形。有没有办法把搜索范围缩小到一个目录?就像用户可以键入文件_name.txt,它将只在一个目录中搜索一样?听起来很简单,但我不知道怎么做。现在,必须在控制台中键入完整路径名,以便进行完整路径名搜索。我只想在控制台中使用文件名。谢谢Jared,这似乎可以工作。不过,我对Java还不是很熟练,所以我不知道如何在代码中实现它,甚至不知道这里发生了什么。我需要花时间来研究这个。但我希望其他人会觉得这很有用。谢谢你的帮助。非常感谢你的帮助!我必须仔细阅读递归,但这看起来很棒。我要把我的问题改为在目录中搜索,而不是在整个计算机中搜索。再次感谢!谢谢你,贾里德,这似乎行得通。不过,我对Java还不是很熟练,所以我不知道如何在代码中实现它,甚至不知道这里发生了什么。我需要花时间来研究这个。但我希望其他人会觉得这很有用。谢谢你的帮助。非常感谢你的帮助!我必须仔细阅读递归,但这看起来很棒。我要把我的问题改为在目录中搜索,而不是在整个计算机中搜索。谢谢 再一次