简体   繁体   English

通过名称在目录中找到特定文件,再将文件保存到本地文件夹

[英]Locate a specific file in a directory by name plus saving a file to the local folder

I would like to locate a file named SAVE.properties. 我想找到一个名为SAVE.properties的文件。 I have looked at different questions that seem like they would answer me, but I can't see that they do. 我看了看似乎他们会回答我的不同问题,但我看不到他们会回答。

For example, I would like to check to see whether or not SAVE.properties exists within a directory (and its subfolders). 例如,我要检查目录(及其子文件夹)中是否存在SAVE.properties。

I would also like to know how I could save a .properties file (and then read it afterwards from this location) to the directory where my program is being run from. 我还想知道如何将.properties文件保存(然后从该位置读取它)到运行程序的目录中。 If it is run from the desktop, it should save the .properties file there. 如果从桌面运行,则应在其中保存.properties文件。

Saving properties can easily be achieved through the use of Properties#store(OutputStream, String) , this allows you to define where the contents is saved to through the use of an OutputStream . 保存属性可以通过使用Properties#store(OutputStream, String)轻松实现,这使您可以定义通过使用OutputStream将内容保存到的位置。

So you could use... 所以你可以使用...

Properties properties = ...;
//...
try (FileOutputStream os = new FileOutputStream(new File("SAVE.properties"))) {
    properties.store(os, "Save");
} catch (IOException exp) {
    exp.printStackTrace();
}

You can also use Properties#load(InputStream) to read the contents of a "properties" file. 您也可以使用Properties#load(InputStream)读取“属性”文件的内容。

Take a closer look at Basic I/O for more details. 详细了解基本I / O。

Locating a File is as simple as using 查找File就像使用一样简单

 File file = new File("SAVE.properties");
 if (file.exists) {...

This checks the current working directory for the existence of the specified file. 这将检查当前工作目录中是否存在指定文件。

Searching the sub directories is little more involved and will require you to use some recursion, for example... 搜索子目录只涉及一点点,例如,需要使用一些递归。

public File find(File path) {

    File save = new File(path, "SAVE.properties");
    if (!save.exists()) {
        save = null;
        File[] dirs = path.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return  pathname.isDirectory();
            }
        });
        for (File dir : dirs) {
            save = find(dir);
            if (save != null) {
                break;
            }
        }
    }
    return save;
}

Using find(new File(".")) will start searching from the current working directory. 使用find(new File("."))将开始从当前工作目录搜索。 Just beware, under the right circumstances, this could search your entire hard disk. 请注意,在适当的情况下,这可能会搜索整个硬盘。

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

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