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

时间:2014-12-09 07:17:45

标签: java file-io

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

目前,我必须每次都使用完整路径名。这不是我的所有代码,但您可以看到我的文件名具有硬编码的String路径名。但是,如果有人想在自己的计算机上运行该程序呢?我试着寻找答案,但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

所有其他方法都在这里,但没有显示以保持简短。

2 个答案:

答案 0 :(得分:2)

如评论中所述,目前有几种工具可用于搜索目录中的文件。但是,为了回答你的问题,我写了一个应该做你想要的简单程序:

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

答案 1 :(得分:1)

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

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

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